在Python Shell中运行程序

68 投票
6 回答
256789 浏览
提问于 2025-04-17 02:18

我有一个演示文件:test.py

在Windows命令行中,我可以通过输入:C:\>test.py来运行这个文件。

那么我该怎么在Python Shell中执行这个文件呢?

6 个回答

20

这要看你的 test.py 文件里写了什么。下面是一个合适的结构:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

如果你保持这个结构,可以在命令行中这样运行它(假设 $ 是你的命令行提示符):

$ python test.py
$ # it will print "running main"

如果你想从 Python 解释器中运行它,只需这样做:

>>> import test
>>> test.main() # this calls the main part of your program

如果你已经在使用 Python,就没有必要使用 subprocess 模块。相反,试着把你的 Python 文件结构设计得既能从命令行运行,也能从 Python 解释器运行。

54

如果你想运行这个脚本,然后停在一个提示符下(这样你就可以查看变量等信息),可以使用:

python -i test.py

这样做会运行脚本,然后让你进入一个Python解释器。

132

Python 2中,可以使用 execfile 来执行文件中的代码:

>>> execfile('C:\\test.py')

而在Python 3中,则需要使用 exec 来执行代码:

>>> exec(open("C:\\test.py").read())

撰写回答