在 Python shell 中运行程序
我有一个演示文件:test.py
。 在 Windows 控制台中,我可以使用以下命令运行该文件: C:\>test.py
如何在 Python Shell 中执行该文件?
I have a demo file: test.py
.
In the Windows Console I can run the file with: C:\>test.py
How can I execute the file in the Python Shell instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于 Python 2 使用 execfile:
使用 < a href="https://docs.python.org/3/library/functions.html#exec" rel="noreferrer">exec 用于Python 3
Use execfile for Python 2:
Use exec for Python 3
如果您想运行脚本并在提示符处结束(以便您可以检查变量等),请使用:
这将运行脚本,然后将您带入 Python 解释器。
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
That will run the script and then drop you into a Python interpreter.
这取决于 test.py 中的内容。以下是适当的结构:
如果保留此结构,您可以在命令行中像这样运行它(假设
$
是您的命令行提示符):如果您想从Python shell,然后您只需执行以下操作:
如果您已经在使用 Python,则无需使用
subprocess
模块。相反,尝试以可以从命令行和 Python 解释器运行的方式构建 Python 文件。It depends on what is in
test.py
. The following is an appropriate structure:If you keep this structure, you can run it like this in the command line (assume that
$
is your command-line prompt):If you want to run it from the Python shell, then you simply do the following:
There is no necessity to use the
subprocess
module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.对于较新版本的 python:
For newer version of python:
如果你想避免每次都编写所有这些,你可以定义一个函数:
然后调用它
If you want to avoid writing all of this everytime, you can define a function :
and then call it
从同一文件夹中,您可以执行以下操作:
From the same folder, you can do: