7

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.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
fortran
  • 74,053
  • 25
  • 135
  • 175

2 Answers2

12

In Python 2, the builtin function execfile does this.

execfile(filename)
Noumenon
  • 5,099
  • 4
  • 53
  • 73
Jason Orendorff
  • 42,793
  • 6
  • 62
  • 96
  • 3
    you have to love python. How do you *exec*ute a *file* in python: execfile. – James Brooks Jan 07 '10 at 19:09
  • 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() – jamk Apr 25 '13 at 13:04
  • 2
    Yep, `execfile()` is gone in Python 3. See [What is an alternative to execfile in Python 3.0?](http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0) – Jason Orendorff Apr 26 '13 at 11:05
  • 1
    With "filename" surrounded by quotes. – Gauthier Mar 24 '14 at 20:20
  • @JamesBrooks Ha - as a Rubyist, I'm like "Why isn't it called execute_file!" – phillyslick Jul 18 '17 at 13:13
3

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).

Noah
  • 21,451
  • 8
  • 63
  • 71
  • 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 :-) – fortran Jan 07 '10 at 17:21