繁体   English   中英

如何从其他目录执行python文件?

[英]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.pymain.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.

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