How to run a python script from IDLE interactive shell? How to run a python script from IDLE interactive shell? python python

How to run a python script from IDLE interactive shell?


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

Python2Built-in function: execfile

execfile('helloworld.py')

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

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

Deprecated since 2.6: popen

import osos.popen('python helloworld.py') # Just run the programos.popen('python helloworld.py').read() # Also gets you the stdout

With arguments:

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

Advance usage: subprocess

import subprocesssubprocess.call(['python', 'helloworld.py']) # Just run the programsubprocess.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 sysif len(sys.argv) > 1:    print(sys.argv[1])


You can use this in python3:

exec(open(filename).read())


The IDLE shell window is not the same as a terminal shell (e.g. running sh or bash). Rather, it is just like being in the Python interactive interpreter (python -i). The easiest way to run a script in IDLE is to use the Open command from the File menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run -> Run Module command (shortcut F5).