用Python sh运行程序

2024-04-25 06:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个演示文件:test.py。 在Windows控制台中,我可以使用以下命令运行文件:C:\>test.py

如何在Python Shell中执行该文件?


Tags: 文件pytest命令windowsshell
3条回答

使用execfile表示Python 2

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

使用exec表示Python 3

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

如果要运行脚本并在提示下结束(以便可以检查变量等),请使用:

python -i test.py

这将运行脚本,然后将您放入Python解释器。

这取决于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 shell运行它,只需执行以下操作:

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

如果您已经在使用Python,那么没有必要使用subprocess模块。相反,尝试以这样一种方式构造您的Python文件:它们可以从命令行和Python解释器运行。

相关问题 更多 >