简体   繁体   English

如何从 IDLE 命令行运行 Python 脚本?

[英]How to run a Python script from IDLE command line?

In a bash shell, I can use 'bash ' or 'source ' to invoke a script by hand.在 bash shell 中,我可以使用“bash”或“source”手动调用脚本。 Can I do the similar thing in the Python IDLE's interactive shell?我可以在 Python IDLE 的交互式 shell 中做类似的事情吗? I know I can go to File >> Open Module, then run it in a separate window, but that's troublesome.我知道我可以转到文件>>打开模块,然后在单独的窗口中运行它,但这很麻烦。

One method I have found is execfile .我发现的一种方法是execfile It has the signature execfile(<filename>,<globals>,<locals>) and runs the file in the same thread as the current IDLE Session.它具有签名execfile(<filename>,<globals>,<locals>)并在与当前 IDLE 会话相同的线程中运行该文件。 This method is Python 2 specific此方法是特定于 Python 2 的

The method the OP is asking for (in a different thread/window) would be to use subprocess to run in a different thread/window. 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'])

These essentially do what nneonneo 's answer does, but using subprocess to execute it in a different thread.这些基本上做nneonneo的回答所做的,但使用subprocess进程在不同的线程中执行它。

If what you meant is executing in the Python IDLE's interactive shell instead of command prompt or command line, then I usually use this approach:如果您的意思是在 Python IDLE 的交互式 shell 中执行而不是在命令提示符或命令行中执行,那么我通常使用这种方法:

python -m idlelib.idle -r "C:/dir1/dir2/Your script.py"

It works well with me.它对我很有效。 Tested on my Windows 10, python 3.7.3.在我的 Windows 10、python 3.7.3 上测试。

Please ensure that you have added your desired python version on your environment variables.请确保您已在环境变量中添加了所需的 Python 版本。

您可以从命令行运行 Python 脚本:

python <script.py>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM