[英]Dynamic module import doesn't work in python - why not?
I'm trying to dynamically import a python script foo.py
into another executable script, which is in a deeply nested folder.我正在尝试将 python 脚本
foo.py
动态导入另一个可执行脚本,该脚本位于深度嵌套的文件夹中。 I'm using我在用着
import os
sys.path.insert(0, '../../../../.')
from foo import Bar
this works, and I can use Bar
happily.这行得通,我可以愉快地使用
Bar
。
I would like to make the script dynamically determine the folder depth eg我想让脚本动态确定文件夹深度,例如
import os
root_path = os.path.relpath(os.popen("git rev-parse --show-toplevel").read()).replace("../reponame", ".")
print(root_path) # prints '../../../../.'
sys.path.insert(0, root_path)
from foo import Bar
However this doesn't work, the script complains it can't find Bar when it is run.但是这不起作用,脚本抱怨它在运行时找不到 Bar 。
Why is this?为什么是这样?
If you debug you see root_path
is actually '../../../../.\n'
.如果您调试,您会看到
root_path
实际上是'../../../../.\n'
。 Remove the \n
删除
\n
root_path.strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.