簡體   English   中英

通過解釋器運行文件會更改當前目錄嗎?

[英]Running a file via the interpreter changes current directory?

當我嘗試$> python ./tools/test.py我收到一個導入錯誤,提示我無法導入在我調用 python 的目錄中存在的模塊。 但是,我可以導入這個模塊, $> python -c "import mod"可以工作。

我依賴於./是(實際上)在 PYTHONPATH 上的事實。

當我在不同目錄中存在的腳本上運行解釋器時,python 對 python 路徑做了什么? 有沒有辦法“鎖定”當前工作目錄,以便導入工作?

我的設置:

./mod.py

x = 5     # just for demonstration purposes

./tools/test.py

from mod import x
# ... snip ... actual content

我從包含mod.pytools/的目錄中調用 python :

$> python -c "from mod import x"      # works fine
$> python tools/test.py

Traceback (most recent call last):

File "tools/test.py", line 1, in <module>
from mod import x
ModuleNotFoundError: No module named 'mod'

請注意,包含mod.pytools的當前目錄不在我的 PYTHONPATH 中。

我依賴於./是(實際上)在 PYTHONPATH 上的事實。

它不是。 它不在PYTHONPATH ,也不在sys.path 當您按文件路徑運行腳本時,腳本的目錄會被添加到sys.path 您可以在Python 命令行 docs 中查看為指定要運行的程序的每種方式添加到sys.path的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM