Hi,
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.
Hi,
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.
>>> execfile('filename.py')
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.
Several ways.
From the shell
python someFile.py
From inside IDLE, hit F5.
If you're typing interactively, try this.
>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module
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.