Tutorial :How do I execute (not import) a python script from a python prompt?



Question:

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.


Solution:1

In Python 2, the builtin function execfile does this.

execfile(filename)  


Solution:2

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »