如何从IDLE交互式shell运行Python脚本?
如何从IDLE交互式shell运行Python脚本?
我如何在IDLE交互式shell中运行python脚本?
以下代码会抛出一个错误:
>>> python helloworld.py SyntaxError: invalid syntax
admin 更改状态以发布 2023年5月23日
Python3:
exec(open('helloworld.py').read())
如果文件不在相同的目录下:
exec(open('./app/filename.py').read())
参见https://stackoverflow.com/a/437857/739577以传递全局/局部变量。
注意:如果您在windows中运行,应该使用双斜杠“//”,否则会出错。
在Python版本中已经弃用
Python2
内置函数:execfile
execfile('helloworld.py')
它通常不能带参数调用。但这是一个解决方法:
import sys sys.argv = ['helloworld.py', 'arg'] # argv[0] should still be the script name execfile('helloworld.py')
自2.6以来已弃用:popen
import os os.popen('python helloworld.py') # Just run the program os.popen('python helloworld.py').read() # Also gets you the stdout
带参数:
os.popen('python helloworld.py arg').read()
高级用法:subprocess
import subprocess subprocess.call(['python', 'helloworld.py']) # Just run the program subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
带参数:
subprocess.call(['python', 'helloworld.py', 'arg'])
详细信息请阅读文档 🙂
使用这个基本的helloworld.py
测试:
import sys if len(sys.argv) > 1: print(sys.argv[1])