如何从IDLE交互式shell运行python脚本?
如何从IDLE交互式shell中运行python脚本?
以下引发错误:
>>> python helloworld.py SyntaxError: invalid syntax 内置函数: 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']) 
阅读文档的详细信息:-)
 testing这个基本的helloworld.py : 
 import sys if len(sys.argv) > 1: print(sys.argv[1]) 
  IDLE shell窗口与terminalshell不同(例如运行sh或bash )。 相反,它就像在Python交互式解释器( python -i )中一样。 在IDLE中运行脚本最简单的方法是使用“ File菜单中的“ Open命令(根据所运行的平台不同而有所不同)将脚本文件加载到IDLE编辑器窗口,然后使用“ Run – > Run Module命令(快捷键F5)。 
你可以在python3中使用它:
 exec(open(filename).read()) 
尝试这个
 import os import subprocess DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py') subprocess.call(['python', DIR]) 
  execFile('helloworld.py')为我完成这项工作。 需要注意的是,如果.py文件不在Python文件夹本身中,则input完整的.py文件的目录名称(至less在Windows上是这种情况) 
 例如, execFile('C:/helloworld.py') 
例如:
 import subprocess subprocess.call("C:\helloworld.py") subprocess.call(["python", "-h"]) 
 在Python 3中,没有execFile 。 可以使用exec内置函数,例如: 
 import helloworld exec('helloworld') 
在IDLE中,以下工作:
 import helloworld 
要在一个python shell(如Idle或Django shell)中运行python脚本,可以使用exec()函数执行以下操作。 Exec()执行一个代码对象参数。 Python中的代码对象是简单编译的Python代码。 所以你必须先编译你的脚本文件,然后使用exec()来执行它。 从你的shell:
>>>file_to_compile = open('/path/to/your/file.py').read() >>>code_object = compile(file_to_compile, '<string>', 'exec') >>>exec(code_object)
我正在使用Python 3.4。 有关详细信息,请参阅编译和执行文档。
我testing了这个,它有点工作:
 exec(open('filename').read()) # Don't forget to put the filename between ' '