dan*_*l__ 45 python executable
我有一个演示文件:test.py.在Windows控制台中,我可以运行以下文件:C:\>test.py
我怎样才能在Python Shell中执行该文件?
phi*_*hag 91
使用execfile for Python 2:
>>> execfile('C:\\test.py')
使用exec for Python 3
>>> exec(open("C:\\test.py").read())
Chr*_*ips 40
如果您想要运行脚本并在提示符处结束(这样您可以检查变量等),那么使用:
python -i test.py
这将运行脚本,然后将您放入Python解释器.
Esc*_*alo 14
这取决于是什么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
subprocess如果您已经在使用Python,则没有必要使用该模块.相反,尝试以这样的方式构建Python文件,即可以从命令行和Python解释器运行它们.
如果你想避免每次都写这些,你可以定义一个函数:
def run(filename):
    exec(open(filename).read())
然后调用它
run('filename.py')
| 归档时间: | 
 | 
| 查看次数: | 192606 次 | 
| 最近记录: |