从 Python 文件路径导入变量

Import Variable from Python FilePath

我正在从我们的一个应用程序中编写一个清理脚本,我需要来自单独目录中 python 文件的一些变量。

现在通常我会去:

from myfile import myvariable
print myvariable

然而,这不适用于目录外的文件。我想要比以下更有针对性的解决方案:

sys.path.append('/path/to/my/dir)
from myfile import myvariable

因为这个目录有很多其他文件,不幸的是它似乎也不能 module = __import__('/path/to/myfile.py') 工作。有什么建议么。我正在使用 python 2.7

编辑,不幸的是这条路径是来自 os.path.join(latest, "myfile.py")

的字符串

您可以使用 imp 模块进行更有针对性的导入。虽然它有一些功能,但我发现唯一允许我访问内部变量的是 load_source.

import imp
import os

filename = 'variables_file.py'
path = '/path_to_file/'

full_path = os.path.join(path_to_file, filename)

foo = imp.load_source(filename, full_path)

print foo.variable_a
print foo.variable_b
...