Problem
I’m attempting to run a Python command file from within the interpreter.
EDIT: Instead of invoking a new process, I’m attempting to leverage variables and settings from that file.
Asked by Adam Matan
Solution #1
Several ways.
Answered by S.Lott
Solution #2
For Python 2:
>>> execfile('filename.py')
For Python 3:
>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())
See the documentation for further information. See this question if you’re using Python 3.0.
For an example of how to access globals from filename.py after it has been executed, see @S.Lott’s answer.
Answered by codeape
Solution #3
exec(open("./path/to/script.py").read(), globals())
This will run a script and place all of its global variables in the global scope of the interpreter (the normal behavior in most scripting environments).
Documentation for Python 3 exec
Answered by Waylon Flinn
Solution #4
I’m surprised I haven’t come across this before. Using the -i option, you can run a file and then leave the interpreter open after it finishes:
| foo.py |
----------
testvar = 10
def bar(bing):
return bing*3
--------
$ python -i foo.py
>>> testvar
10
>>> bar(6)
18
Answered by Bennett Talpers
Solution #5
Simply importing the file with import filename (without the.py extension; it must be in the same directory or on your PYTHONPATH) will run it, making all of its variables, functions, classes, and other features available in the filename.variable namespace.
So, if you have cheddar.py and the variables spam and eggs, you can import them, access the variable with cheddar.spam, and run the function with cheddar.eggs ()
If you have code outside of a function in cheddar.py, it will be executed immediately, however designing apps that run code on import will make it difficult to reuse your code. Put everything into functions or classes if at all possible.
Answered by mikl
Post is based on https://stackoverflow.com/questions/1027714/how-to-execute-a-file-within-the-python-interpreter