Home > Article > Backend Development > How to Run a Python Script with Arguments from Another Script?
Running Python Scripts with Arguments from Another Script
It is possible to execute one Python script from another, passing arguments along the way. Suppose you want to run a script (script2.py) that iterates through values (0-3) from another script (script1.py). How can this be achieved?
To execute script2.py from script1.py with arguments, use the os.system() command. For example:
<code class="python">import os # Run script2.py with argument 1 os.system("script2.py 1") # Run script2.py with argument 2 os.system("script2.py 2")</code>
Using execfile(), as you tried, is not suitable as it executes Python statements in the current context, leaving sys.argv unchanged.
Note that this method does not allow you to directly access or modify variables in script2.py from script1.py. If you need to exchange data between scripts, consider using functions or modules instead.
The above is the detailed content of How to Run a Python Script with Arguments from Another Script?. For more information, please follow other related articles on the PHP Chinese website!