如何从 IDLE 交互式 shell 运行 python 脚本? [英] How to run a python script from IDLE interactive shell?

查看:68
本文介绍了如何从 IDLE 交互式 shell 运行 python 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下抛出错误:

<预><代码>>>>蟒蛇你好世界.py语法错误:无效语法

解决方案

Python3:

exec(open('helloworld.py').read())

如果您的文件不在同一个目录中:

exec(open('./app/filename.py').read())

有关传递全局/局部变量的信息,请参阅https://stackoverflow.com/a/437857/739577.><小时>

在弃用的 Python 版本中

Python2内置函数:execfile

execfile('helloworld.py')

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

导入系统sys.argv = ['helloworld.py', 'arg'] # argv[0] 应该仍然是脚本名称execfile('helloworld.py')

<小时>

自 2.6 起已弃用:popen

导入操作系统os.popen('python helloworld.py') # 运行程序即可os.popen('python helloworld.py').read() # 也给你标准输出

带参数:

os.popen('python helloworld.py arg').read()

<小时>

高级用法:子进程

导入子流程subprocess.call(['python', 'helloworld.py']) # 运行程序subprocess.check_output(['python', 'helloworld.py']) # 也让你得到标准输出

带参数:

subprocess.call(['python', 'helloworld.py', 'arg'])

阅读文档了解详情:-)

<小时>

用这个基本的helloworld.py测试:

导入系统如果 len(sys.argv) >1:打印(sys.argv[1])

How do I run a python script from within the IDLE interactive shell?

The following throws an error:

>>> python helloworld.py
SyntaxError: invalid syntax

解决方案

Python3:

exec(open('helloworld.py').read())

If your file not in the same dir:

exec(open('./app/filename.py').read())

See https://stackoverflow.com/a/437857/739577 for passing global/local variables.


In deprecated Python versions

Python2 Built-in function: execfile

execfile('helloworld.py')

It normally cannot be called with arguments. But here's a workaround:

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


Deprecated since 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

With arguments:

os.popen('python helloworld.py arg').read()


Advance usage: subprocess

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

With arguments:

subprocess.call(['python', 'helloworld.py', 'arg'])

Read the docs for details :-)


Tested with this basic helloworld.py:

import sys
if len(sys.argv) > 1:
    print(sys.argv[1])

这篇关于如何从 IDLE 交互式 shell 运行 python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆