run program in Python shell

PythonExecutable

Python Problem Overview


I have a demo file: test.py. In the Windows Console I can run the file with: C:\>test.py

How can I execute the file in the Python Shell instead?

Python Solutions


Solution 1 - Python

Use execfile for Python 2:

>>> execfile('C:\\test.py')

Use exec for Python 3

>>> exec(open("C:\\test.py").read())

Solution 2 - Python

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

Solution 3 - Python

It depends on what is in test.py. The following is an appropriate structure:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):

$ python test.py
$ # it will print "running main"

If you want to run it from the Python shell, then you simply do the following:

>>> import test
>>> test.main() # this calls the main part of your program

There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.

Solution 4 - Python

For newer version of python:

exec(open(filename).read())

Solution 5 - Python

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

Solution 6 - Python

From the same folder, you can do:

import test

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondaniel__View Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonChris PhillipsView Answer on Stackoverflow
Solution 3 - PythonEscualoView Answer on Stackoverflow
Solution 4 - PythonVictorView Answer on Stackoverflow
Solution 5 - PythonHugo TrentesauxView Answer on Stackoverflow
Solution 6 - PythonBrendan LongView Answer on Stackoverflow