I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing source in bash or sh.
2 Answers
In Python 2, the builtin function execfile does this.
execfile(filename)
5 Comments
James Brooks
you have to love python. How do you execute a file in python: execfile.
jamk
in python 3 it doesn t work you have to use your own module for that like this import sys class process(): def call__(self,filename,globals=None, locals=None): import sys if globals is None: globals = sys._getframe(1).f_globals if locals is None: locals = sys._getframe(1).f_locals with open(filename, "r") as fh: exec(fh.read()+"\n", globals, locals) sys.modules[__name] = process()
Jason Orendorff
Yep,
execfile() is gone in Python 3. See What is an alternative to execfile in Python 3.0?Gauthier
With "filename" surrounded by quotes.
phillyslick
@JamesBrooks Ha - as a Rubyist, I'm like "Why isn't it called execute_file!"
If you're running ipython (which I highly recommend for interactive python sessions), you can type:
%run filename
or
%run filename.py
to execute the module (rather than importing it). You'll get file-name completion, which is great for ReallyLongModuleName.py (not that you'd name your modules like that or anything).
1 Comment
fortran
thanks for the suggestion, I usually use ipython, but unluckily for this task I needed to debug a C library that was called from python via Ctypes. So I needed to load the python binary in gdb, run it, import ctypes, load the library, write down the load address, break to gdb, add the library symbols, set the breakpoints, continue executing python and finally load the module... using ipython would have added an extra step, as it's not a binary itself that can be loaded directly in gdb, but another python script :-)