![](/img/trans.png)
[英]Python script works when I run from IDLE but not in command line?
[英]How to run a Python script from IDLE command line?
在 bash shell 中,我可以使用“bash”或“source”手動調用腳本。 我可以在 Python IDLE 的交互式 shell 中做類似的事情嗎? 我知道我可以轉到文件>>打開模塊,然后在單獨的窗口中運行它,但這很麻煩。
我發現的一種方法是execfile
。 它具有簽名execfile(<filename>,<globals>,<locals>)
並在與當前 IDLE 會話相同的線程中運行該文件。 此方法是特定於 Python 2 的
OP 要求的方法(在不同的線程/窗口中)是使用subprocess
進程在不同的線程/窗口中運行。
import subprocess #any of these will run the file. Pick the one that best suits you. subprocess.call(['python','filename.py']) subprocess.check_call(['python','filename.py']) subprocess.Popen(['python','filename.py'])
這些基本上做nneonneo的回答所做的,但使用subprocess
進程在不同的線程中執行它。
如果您的意思是在 Python IDLE 的交互式 shell 中執行而不是在命令提示符或命令行中執行,那么我通常使用這種方法:
python -m idlelib.idle -r "C:/dir1/dir2/Your script.py"
它對我很有效。 在我的 Windows 10、python 3.7.3 上測試。
請確保您已在環境變量中添加了所需的 Python 版本。
您可以從命令行運行 Python 腳本:
python <script.py>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.