[英]python __import__ all files in folder not working
from os import listdir
modo= [name.split(".py")[0] for name in listdir("scripts") if name.endswith(".py")]
modules = {}
for modu in modo:
modules[modu] = __import__(modu)
test_samp.function("test")
Hello! 你好! If, say "test_samp.py" exists in the scripts directory, why does this not allow me to run test_samp.function("test")?
如果说脚本目录中存在“ test_samp.py”,为什么不允许我运行test_samp.function(“ test”)? It returns:
它返回:
Unhandled exception in thread started by <function function at 0x8e39204>
Traceback (most recent call last):
File "test_this.py", line 6, in function
test_samp.function("test")
NameError: global name 'test_samp' is not defined
You have two problems in your code: 您的代码中有两个问题:
__import__
doesn't import into global namespace, it returns a module __import__
不导入全局名称空间,它返回一个模块 test_samp
while it's scripts.test_samp
test_samp
中导入scripts.test_samp
What you actually want is: 您真正想要的是:
scripts = __import__("scripts", fromlist=modo)
scripts.test_samp.function("test")
Above __import__
returns scripts
package with all the sub-modules loaded. 在
__import__
上面,返回加载了所有子模块的scripts
包。 Don't forget to make scripts
directory a package by creating __init__.py
in it. 不要忘记通过在其中创建
__init__.py
来使scripts
目录成为一个包。
See also: Why does Python's __import__ require fromlist? 另请参见: 为什么Python的__import__需要fromlist?
Your are not defining test_samp
you are defining modules['test_samp']
. 您没有在定义
test_samp
而是在定义modules['test_samp']
。 Plus if it's in scripts you need to import scripts.test_samp
另外,如果它在脚本中,则需要导入
scripts.test_samp
in yor case use a package.Add an empty (or not) __init__.py
(with 2 underscores). 在这种情况下,请使用一个软件包。添加一个空(或不空)
__init__.py
。 __init__.py
(带2个下划线)。 and use import scripts
. 并使用
import scripts
。 Access your function with scripts.test_samp.function("test")
. 使用
scripts.test_samp.function("test")
访问您的函数。 And you could use reload(scripts)
to reload all of the package. 您可以使用
reload(scripts)
重新加载所有程序包。
您可以使用以下命令运行它:
modules["test_samp"].function("test")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.