如何从IDLE交互式shell运行python脚本?

92 python shell command-line python-idle

如何从IDLE交互式shell中运行python脚本?

以下引发错误:

>>> python helloworld.py
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Hug*_*lle 123

内置函数:execfile

execfile('helloworld.py')
Run Code Online (Sandbox Code Playgroud)

它通常不能用参数调用.但这是一个解决方法:

import sys
sys.argv = ['helloworld.py', 'arg']  # argv[0] should still be the script name
execfile('helloworld.py')
Run Code Online (Sandbox Code Playgroud)

自2.6以来不推荐使用:popen

exec(open('helloworld.py').read())
Run Code Online (Sandbox Code Playgroud)

有参数:

import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout
Run Code Online (Sandbox Code Playgroud)

高级用法:子进程

os.popen('python helloworld.py arg').read()
Run Code Online (Sandbox Code Playgroud)

有参数:

import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
Run Code Online (Sandbox Code Playgroud)

阅读文档了解详情:-)


用这个基本测试helloworld.py:

subprocess.call(['python', 'helloworld.py', 'arg'])
Run Code Online (Sandbox Code Playgroud)

  • 你能不能用命令行参数添加一个例子. (2认同)
  • 不适用于 Python3 并且提问者没有明确指定 Python 版本 (2认同)
  • 为 Python3 添加了“exec” (2认同)

Fac*_*alm 30

你可以在python3中使用它:

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


Ned*_*ily 21

IDLE shell窗口与终端shell不同(例如,运行shbash).相反,它就像是在Python交互式解释器(python -i)中.在IDLE中运行脚本的最简单方法是使用菜单中的Open命令File(这可能会有所不同,具体取决于您运行的平台)将脚本文件加载到IDLE编辑器窗口,然后使用Run- > Run Module命令(快捷方式) F5).

  • 不幸的是,不,在传递命令行参数时,在IDLE中运行Python文件并不容易.IDLE有一个长期存在的公开问题(http://bugs.python.org/issue5680).测试的一种解决方法是在程序的最开始手动初始化`sys.argv`,例如,在通常的`if __name__ =="__main __"`样板下. (3认同)

Ser*_*sov 5

试试这个

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])
Run Code Online (Sandbox Code Playgroud)


Leo*_*ard 5

最简单的方法

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3
Run Code Online (Sandbox Code Playgroud)