'Passing argumnets to one script.py file from another script.py file
I want script1.py to loop a list and pass its output as an argument for another python file.
script1.py
list = ['1','2','3']
for x in list:
subprocess.call("python3 script2.py", shell=True)
I want script2.py to use x as its input
Solution 1:[1]
Let's say the script2.py file is a file such as:
- script2.py
import sys
argv = sys.argv
print(argv)
As you can see, this python file just shows the input argument. Note that the first argument always will be the file name.
Now suppose we want to loop over a list and pass the list elements to this script file as an argument. What we need to do simply is what follows:
- script1.py
import subprocess
myList = ["arg_1", "arg_2", "arg_3"]
for x in myList:
result = subprocess.run(["python", 'script2.py', x], stdout=subprocess.PIPE)
print(result.stdout.decode("UTF-8").strip())
Note that script1.py and script2.py are in the same folder(directory).
Output
['script2.py', 'arg_1']
['script2.py', 'arg_2']
['script2.py', 'arg_3']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amirhossein Kiani |
