2017-08-14 125 views
0

我在一個文本文件「program.py」中寫了程序。我將這個文件保存在桌面上。我想通過命令行來執行此Python命令行

Microsoft Windows [Version 10.0.15063] 
(c) 2017 Microsoft Corporation. All rights reserved. 

C:\Users\x0266161>cd C:\Users\x0266161\Desktop\ 

C:\Users\x0266161\Desktop>python program.py 
hello world 

Now is it possible for me to execute the program without changing to the directory where program is stored. 

when I try I am getting below error 

C:\Users\x0266161\Desktop>cd .. 

C:\Users\x0266161>cd .. 

C:\Users>cd .. 

C:\>python program.py 
python: can't open file 'program.py': [Errno 2] No such file or directory 

C:\> 

我有環境變量設置爲這個路徑C:\用戶\ x0266161 \桌面。

回答

0

,當你鍵入

C:>蟒蛇program.py

要傳遞的文件 「program.py」 作爲參數來解釋。 事實上,只有在當前目錄中才能訪問此文件。

現在,我不是普通的Windows用戶,但是您的program.py必須是可執行的,並且應該有一個shebang(在Linux或Windows + cygwin上)可以從路徑運行。

這個特殊的職位能夠幫助你:https://stackoverflow.com/a/7574585/8462076

否則,你可以使用像py2exe創建一個可執行文件(即MS移植可執行的.exe文件)

另外,如果你有文件關聯。 py文件和你的python解釋器,你可以簡單地雙擊運行它。

希望它有幫助。

0

只要在它前面運行program.py而沒有python。 Windows將爲該程序而不是Python搜索PATH,並且由於Python將.py註冊爲它處理的文件,因此Python將隨該文件一起運行。

如果將.py添加到PATHEXT環境變量中,那麼也可以只輸入program