Reputation: 23
I am trying to call a Python script from another. I am using the subprocess
-module and calling it like this:
subprocess.call(["python","script.py","parameter_name parameter_value"], shell=False)
The thing is when I call it this way it works fine for a single parameter. When I have multiple parameters I tried running it this way
subprocess.call(["python","script.py","parameter_one_name parameter_one_value", "parameter_two_name parameter_two_value"], shell=False)
This does not work for some reason and the script does not give out any error message as well. So, I tried doing this
os.system("python script.py parameter_one_name parameter_one_value parameter_two_name parameter_two_value)
This works and the script works as expected. The question I have is is it possible to call the script when the parameters are stored in a string? For example,
parameter = parameter_one_name parameter_one_value+parameter_two_name parameter_two_value)
execute script with parameter
I could not find anything so far on SO, so it would be a great help if anyone could help.
Upvotes: 2
Views: 5754
Reputation: 414825
If parameters are in a dictionary d
:
import sys
import subprocess
params = [x for pair in d.items() if all(pair) for x in pair]
subprocess.check_call([sys.executable, 'script.py'] + params)
Upvotes: 1
Reputation: 43208
You should be passing each parameter's value as a separate item in the list:
subprocess.call(["python","script.py","parameter_one_name","parameter_one_value", "parameter_two_name","parameter_two_value"], shell=False)
If needed, you can compose your parameter list from smaller lists:
param1 = ["parameter_one_name", "parameter_one_value"]
param2 = ["parameter_two_name", "parameter_two_value"]
subprocess.call(["python","script.py"] + param1 + param2, shell=False)
I have no idea how exactly your scenario works when you call it with a single parameter + value in a string; it shouldn't, but without seeing the actual values you're passing, it's impossible to tell.
Upvotes: 1