简体   繁体   English

从Python FilePath导入变量

[英]Import Variable from Python FilePath

I'm writing a clean up script from one of our applications and I need a few variables from a python file in a separate directory. 我正在从我们的一个应用程序编写一个清理脚本,我需要一个python文件中的一些变量在一个单独的目录中。

Now normally I would go: 现在通常我会去:

from myfile import myvariable
print myvariable

However this doesn't work for files outside of the directory. 但是,这不适用于目录之外的文件。 I'd like a more targeted solution than: 我想要一个比以下更有针对性的解决方案:

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

As this directory has a lot of other files, unfortunately it doesn't seem like module = __import__('/path/to/myfile.py') works either. 由于这个目录有很多其他文件,不幸的是它似乎不是module = __import__('/path/to/myfile.py') Any suggestions. 有什么建议。 I'm using python 2.7 我正在使用python 2.7

EDIT, this path is unfortunately a string from os.path.join(latest, "myfile.py") 编辑,这条路径不幸是os.path.join(latest, "myfile.py")一个字符串os.path.join(latest, "myfile.py")

You can do a more targeted import using the imp module. 您可以使用imp模块进行更有针对性的导入。 While it has a few functions, I found the only one that allowed me access to internal variables was load_source . 虽然它有一些功能,但我发现唯一允许我访问内部变量的是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
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM