简体   繁体   English

python导入特定文件

[英]python import specific file

trying to import a specific file called environment.py the issue is that I have this file in more than one location the way i'm loading all my file variables (more than 20 variables in each file) is : 尝试导入一个名为environment.py的特定文件,问题是我将这个文件放置在多个位置(我加载所有文件变量(每个文件中有20个以上变量))的方式是:

from environment import *

the thing is , I have the environment.py in 2 directories and my sys.path includes both of them. 问题是,我在两个目录中都有environment.py ,而sys.path包括两个目录。 python loads the file from the first location in the list. python从列表中的第一个位置加载文件。

Tried 试着

import os, sys, imp
path = os.path.dirname(os.path.abspath(__file__))
file = path + '/environment.py'
foo = imp.load_source('*',file)

But then my variables are loaded into foo and not directly. 但是然后我的变量被加载到foo而不是直接加载。

Any ideas how to force import * from the right location 任何想法如何强制从正确的位置import *

If you want to continue with what you started and this is in the global scope, you could add this to the end: 如果要继续开始的工作,并且这是在全局范围内,则可以在末尾添加:

for varName in dir(foo):
    globals()[varName] = getattr(foo, varName)

Now all of the variables that were defined in environment.py are in your global namespace. 现在,在environment.py中定义的所有变量都在全局命名空间中。

Although it's probably easier to just do what Tom Karzes suggested and do: 尽管按照汤姆·卡兹斯的建议做,可能会更容易:

import os, sys
sys.path.insert(0, path)
from environment import *

# Optional. Probably harmless to leave it in your path.
del sys.path[0]

Put it in a module 将其放在模块中

/module
    __init__.py
    environment.py

That way you can call 这样你可以打电话

from module.environment import *

And there should be no issue having two modules with environment.py in them, the only difference being the import call. 并且在其中包含两个带有environment.py模块应该没有问题,唯一的区别是导入调用。 Is that what you mean? 你是这个意思吗?

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

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