Run a Python script from another Python script, passing in arguments [duplicate]
This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:
In an ideal world, you will be able to call a function inside
for i in range(whatever): script1.some_function(i)
If necessary, you can hack
sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.
import contextlibdef redirect_argv(num): sys._argv = sys.argv[:] sys.argv=[str(num)] yield sys.argv = sys._argvwith redirect_argv(1): print(sys.argv)
I think this is preferable to passing all your data to the OS and back; that's just silly.
Ideally, the Python script you want to run will be set up with code like this near the end:
def main(arg1, arg2, etc): # do whatever the script doesif __name__ == "__main__": main(sys.argv, sys.argv, sys.argv)
In other words, if the module is called from the command line, it parses the command line options and then calls another function,
main(), to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)
If you want to call such a script from another Python script, however, you can simply
import it and call
modulename.main() directly, rather than going through the operating system.
os.system will work, but it is the roundabout (read "slow") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.