run program in Python shell run program in Python shell python python

run program in Python shell


Use execfile for Python 2:

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

Use exec for Python 3

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


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.


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

# suppose this is your 'test.py' filedef 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.