How to run a python script from IDLE interactive s

2020-01-27 09:32发布

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

The following throws an error:

>>> python helloworld.py
SyntaxError: invalid syntax

13条回答
手持菜刀,她持情操
2楼-- · 2020-01-27 10:03

EASIEST WAY

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3
查看更多
成全新的幸福
3楼-- · 2020-01-27 10:03

In IDLE, the following works :-

import helloworld

I don't know much about why it works, but it does..

查看更多
家丑人穷心不美
4楼-- · 2020-01-27 10:04

For example:

import subprocess

subprocess.call("C:\helloworld.py")

subprocess.call(["python", "-h"])
查看更多
闹够了就滚
5楼-- · 2020-01-27 10:07

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')

Python3: alternative to exefile:

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

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


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])
查看更多
叛逆
6楼-- · 2020-01-27 10:09

To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

I'm using Python 3.4. See the compile and exec docs for detailed info.

查看更多
劫难
7楼-- · 2020-01-27 10:13

I tested this and it kinda works out :

exec(open('filename').read())  # Don't forget to put the filename between ' '
查看更多
登录 后发表回答