I'm trying to execute a file with Python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.
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. If you are using Python 3.0, see this question.
See answer by @S.Lott for an example of how you access globals from filename.py after executing it.
I'm trying to use variables and settings from that file, not to invoke a separate process.
Well, simply importing the file with import filename
(minus .py, needs to be in the same directory or on your PYTHONPATH
) will run the file, making its variables, functions, classes, etc. available in the filename.variable
namespace.
So if you have cheddar.py
with the variable spam and the function eggs – you can import them with import cheddar
, access the variable with cheddar.spam
and run the function by calling cheddar.eggs()
If you have code in cheddar.py
that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.
From my view, the best way is:
import yourfile
and after modifying yourfile.py
reload(yourfile)
or
import imp;
imp.reload(yourfile) in python3
but this will make the function and classes looks like that: yourfile.function1, yourfile.class1.....
If you cannot accept those, the finally solution is:
reload(yourfile)
from yourfile import *
I am not an expert but this is what I noticed:
if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter.
Supposing you desire the following features:
__name__ == '__main__'
is True so scripts behave properly as scripts.The exec(open('foo.py').read())
fails feature 1
The import foo
strategy fails feature 2
To get both, you need this:
source = open(filename).read()
code = compile(source, filename, 'exec')
exec(code)