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.

2 Answers 2

12

In Python 2, the builtin function execfile does this.

execfile(filename)
Sign up to request clarification or add additional context in comments.

5 Comments

you have to love python. How do you execute a file in python: execfile.
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()
Yep, execfile() is gone in Python 3. See What is an alternative to execfile in Python 3.0?
With "filename" surrounded by quotes.
@JamesBrooks Ha - as a Rubyist, I'm like "Why isn't it called execute_file!"
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).

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.