是否有可能在交互模式下执行 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4624416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a possibility to execute a Python script while being in interactive mode
提问by lennykey
Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
通常,您可以执行 Python 脚本,例如:python myscript.py,但是如果您处于交互模式,如何在文件系统上执行 Python 脚本?
>>> exec(File) ???
It should be possible to execute the script more than one time.
应该可以多次执行脚本。
采纳答案by fn.
Use execfile('script.py')but it only work on python 2.x, if you are using 3.0 try this
使用execfile('script.py')但它只适用于 python 2.x,如果你使用 3.0 试试这个
回答by richo
import filewithout the .py extension will do it, however __name__will not be "__main__"so if the script does any checks to see if it's being run interactively you'll need to bypass them.
import file没有.py扩展名会做,但__name__不会是"__main__"这样,如果脚本做任何检查,看它是否正在运行交互式你需要绕过它们。
Alternately, if you're wanting to have a look at the environment after the script runs try python -i script.py
或者,如果您想在脚本运行后查看环境,请尝试 python -i script.py
EDIT: To load it again
编辑:再次加载
file = reload(file)
file = reload(file)
回答by Silver Light
You can run any system command using python:
您可以使用 python 运行任何系统命令:
>>>from subprocess import Popen
>>>Popen("python myscript.py", shell=True)
回答by Sylvain Defresne
You can also use the subprocessmodule. Something like:
您也可以使用该subprocess模块。就像是:
>>> import subprocess
>>> proc = subprocess.Popen(['./script.py'])
>>> proc.communicate()
回答by Thomas K
You might want to look into IPython, a more powerful interactive shell. It has various "magic" commands including %run script.py(which, of course, runs the script and leaves any variables it defined for you to examine).
您可能想要研究IPython,这是一个更强大的交互式 shell。它有各种“魔法”命令,包括%run script.py(当然,它运行脚本并留下它定义的任何变量供您检查)。
回答by Cipher
The easiest way to do it is to use the osmodule:
最简单的方法是使用os模块:
import os
os.system('python script.py')
In fact os.system('cmd')to run shell commands. Hope it will be enough.
实际上os.system('cmd')是运行shell命令。希望它足够了。

