是否有可能在交互模式下执行Python脚本
通常你可以执行Python脚本,例如:python myscript.py
,但是如果你处于交互模式,如何在文件系统上执行Python脚本呢?
>>> exec(File) ???
应该可以多次执行该脚本。
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?
>>> exec(File) ???
It should be possible to execute the script more than one time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最简单的方法是使用 os 模块:
实际上 os.system('cmd') 来运行 shell 命令。希望这足够了。
The easiest way to do it is to use the
os
module:In fact
os.system('cmd')
to run shell commands. Hope it will be enough.使用
execfile('script.py')
但它仅适用于 python 2.x,如果您使用 3.0,请尝试exec(open('script.py').read())
Use
execfile('script.py')
but it only work on python 2.x, if you are using 3.0 tryexec(open('script.py').read())
不带 .py 扩展名的
import file
可以做到这一点,但是__name__
不会是"__main__"
因此,如果脚本执行任何检查以查看是否它是以交互方式运行的,你需要绕过它们。或者,如果您想在脚本运行后查看环境,请尝试
python -i script.py
编辑:再次加载它
file = reload(file)
import file
without 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.Alternately, if you're wanting to have a look at the environment after the script runs try
python -i script.py
EDIT: To load it again
file = reload(file)
您可能想研究一下 IPython,一个更强大的交互式 shell。它有各种“神奇”命令,包括
%run script.py
(当然,它会运行脚本并留下它定义的任何变量供您检查)。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).您还可以使用
subprocess
模块。像这样的东西:You can also use the
subprocess
module. Something like:您可以使用 python 运行任何系统命令:
You can run any system command using python: