# 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
使用execfile表示Python 2:
使用exec表示Python 3
如果要运行脚本并在提示下结束(以便可以检查变量等),请使用:
这将运行脚本,然后将您放入Python解释器。
这取决于
test.py
中的内容。以下是适当的结构:如果保留此结构,则可以在命令行中这样运行它(假设
$
是命令行提示符):如果要从Python shell运行它,只需执行以下操作:
如果您已经在使用Python,那么没有必要使用
subprocess
模块。相反,尝试以这样一种方式构造您的Python文件:它们可以从命令行和Python解释器运行。相关问题 更多 >
编程相关推荐