![](/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.