![](/img/trans.png)
[英]How can I execute a file (that imports other modules) from a Python script in a different directory without using relative imports in the file?
[英]How to execute python file from other directory?
我有这个结构:
│
├ main.py
├ dir
| ├─ data.txt
| └─ other.py
来自other.py的内容:
print(open('data.txt', 'utf-8').read())
我运行main.py
它必须以dir/other.py
。
但是other.py
for other.py
需要data.txt
。 有没有启动方式other.py
从main.py
,而不是编辑other.py
?
注意
用户必须能够手动启动other.py且没有任何错误
为此,您可以使用import关键字。 您要做的就是在dir目录下创建一个__init__.py脚本,该脚本会将目录定义为库。 然后,您可以在主脚本中使用导入其他文件。
建议使用以下代码片段修改others.py脚本
if __name__ == '__main__':
// do stuff
否则,它将在您每次导入时执行该库
这要简单得多。 您只需要使用os.chdir(“ ./ dir”)来更改目录。 之后,您可以运行简单的导入,脚本将被执行。
./dir/other.py:
print("Module starts")
print(open('data', 'r').read())
print("Module ends")
./main.py
print("Main start")
import os
os.chdir("./dir")
from others import other
print("Main end" )
您可以from dir.other import *
其他文件,例如from dir.other import *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.