在Python shell中运行程序

dan*_*l__ 45 python executable

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

我怎样才能在Python Shell中执行该文件?

phi*_*hag 91

使用execfile for Python 2:

>>> execfile('C:\\test.py')
Run Code Online (Sandbox Code Playgroud)

使用exec for Python 3

>>> exec(open("C:\\test.py").read())
Run Code Online (Sandbox Code Playgroud)

  • 在版本3(我的版本)中,等效的是:exec(open("C:\\ test.py").read()).谢谢! (24认同)
  • @loops我得到:`SyntaxError :( Unicode错误)'unicodeescape'编解码器无法解码2-3位的字节:截断\ uXXXX excape`.这是什么意思?我尝试将.py文件的编码更改为Unicode,但没有任何效果. (2认同)

Chr*_*ips 40

如果您想要运行脚本并在提示符处结束(这样您可以检查变量等),那么使用:

python -i test.py
Run Code Online (Sandbox Code Playgroud)

这将运行脚本,然后将您放入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()
Run Code Online (Sandbox Code Playgroud)

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

$ python test.py
$ # it will print "running main"
Run Code Online (Sandbox Code Playgroud)

如果您想从Python shell运行它,那么您只需执行以下操作:

>>> import test
>>> test.main() # this calls the main part of your program
Run Code Online (Sandbox Code Playgroud)

subprocess如果您已经在使用Python,则没有必要使用该模块.相反,尝试以这样的方式构建Python文件,即可以从命令行和Python解释器运行它们.


Vic*_*tor 6

对于较新版本的python:

exec(open(filename).read())
Run Code Online (Sandbox Code Playgroud)


Hug*_*aux 5

如果你想避免每次都写这些,你可以定义一个函数:

def run(filename):
    exec(open(filename).read())
Run Code Online (Sandbox Code Playgroud)

然后调用它

run('filename.py')
Run Code Online (Sandbox Code Playgroud)