Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Python script from another Python script, passing in arguments [duplicate]

Tags:

python

I want to run a Python script from another Python script. I want to pass variables like I would using the command line.

For example, I would run my first script that would iterate through a list of values (0,1,2,3) and pass those to the 2nd script script2.py 0 then script2.py 1, etc.

I found Stack Overflow question 1186789 which is a similar question, but ars's answer calls a function, where as I want to run the whole script, not just a function, and balpha's answer calls the script but with no arguments. I changed this to something like the below as a test:

execfile("script2.py 1") 

But it is not accepting variables properly. When I print out the sys.argv in script2.py it is the original command call to first script "['C:\script1.py'].

I don't really want to change the original script (i.e. script2.py in my example) since I don't own it.

I figure there must be a way to do this; I am just confused how you do it.

like image 934
Gern Blanston Avatar asked Sep 23 '10 19:09

Gern Blanston


People also ask

Can you run the same python file twice?

You can run multiple instances of a python script from a shell however from within a python program without the use of multithreading/multiprocessing the GIL limitation will impact what you are trying to do.

How do I run a python script from passing parameters?

You can use the command line arguments by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.


1 Answers

Try using os.system:

os.system("script2.py 1") 

execfile is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv didn't change for you.

like image 65
Greg Hewgill Avatar answered Oct 12 '22 04:10

Greg Hewgill