Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 781
fortran Avatar asked Jan 07 '10 15:01

fortran


People also ask

How do I run a Python script from the command-line?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

Why is Python running a module when I import it?

It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that.

How do I run a Python script in Windows 10?

Go to your Start menu (lower left Windows icon), type "Microsoft Store", select the link to open the store. Once the store is open, select Search from the upper-right menu and enter "Python". Select which version of Python you would like to use from the results under Apps.

Does importing a Python script run it?

When you import a module in Python, all the code in it will be run, and all the variables in that module will be stuck on that module object.


1 Answers

In Python 2, the builtin function execfile does this.

execfile(filename)
like image 187
Jason Orendorff Avatar answered Sep 21 '22 18:09

Jason Orendorff