[英]calling python interpreter with .py file as command line argument not working
我已將路徑環境變量設置為包含 python 解釋器以及我的“python_scripts”文件夾。 我可以從我機器上的任何地方單獨調用 python 解釋器或位於“python_scripts”文件夾中的任何 .py 文件,如下所示:
C:\> python.exe
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
或者
C:\> test_code.py
他們都工作正常。 但是,當我調用 python 解釋器后跟腳本名稱時:
C:\> python.exe test_code.py
除非我位於“python_scripts”文件夾中,否則它會返回以下錯誤:
python: can't open file 'test_code.py': [Errno 2] No such file or directory
為什么會發生這種情況?
如果您使用C:\\> python.exe test_code.py
它將在您當前目錄中查找test_code.py
。 如果您將參數傳遞給python.exe
它需要是存在文件的有效絕對或相對路徑。
這意味着該文件位於您的 Windows %PATH%
變量中。 當您執行python.exe
,它會在各種地方進行查找。 例如,如果您的PATH
看起來像: C:\\;"C:\\Program Files\\Python 3\\";C:\\Users\\user\\python_scripts
,它會嘗試C:\\python.exe
,然后嘗試C:\\Program Files\\Python 3\\python.exe
並找到 Python。
當您執行test_code.py
,它會發現它為C:\\Users\\user\\python_scripts\\test_code.py
(例如)。
當您調用python.exe
,它只會讀取文件名,而不會嘗試解析路徑。
Python 使用不同的導入路徑,可以將其視為sys.path
。
您可以使用python\\Lib\\site-packages
的.pth
文件擴展它。
例如,如果您添加具有以下內容的user_pth.pth
文件:
C:\Users\user\python_scripts\
然后你可以從任何文件中import test_code
。
因此,您可以通過將代碼作為模塊運行來調用 python 導入程序:
python.exe -m test_code
您應該為 python.exe 提供腳本 python.exe 的完整路徑。 c:\\test_code.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.