Reputation: 391
I have a simple def stored in C:/Users/admin/Desktop/sample.py,
import time, os
def cook(sec):
print('cooking started')
time.sleep(sec)
print(f'cooking done in {sec} sec(s) on process: {os.getpid()}')
My goal is to use subprocess library to run sample.py, I use anaconda as my interpreter
import subprocess
path = 'C:/ProgramData/Anaconda3/python.exe C:/Users/admin/Desktop/sample.py'
subprocess.run(path, shell=True)
How can I pass in a list of args to subprocess.run? I tried to join path with a list [cook(1), cook(2), cook(3)].failed. What shall I do? Ideally, pass in a list and run the def one by one. Appreciated.
Upvotes: 0
Views: 932
Reputation: 1015
A very simple example:
subprocess.run(["/path/to/python.exe", "/path/to/sample.py", "2", "3", "4"])
Your sample.py
import time
import os
import sys
def cook(sec):
print('cooking started')
time.sleep(sec)
print(f'cooking done in {sec} sec(s) on process: {os.getpid()}')
if __name__ == "__main__":
# See argparser module, this is just a simple example without using argparser
# Argument 0 is always the name of your file
# Argument 1 is the number of cookings
# Argument 2 and beyond are the seconds for those cookings
numberOfCookings = int(sys.argv[1])
for i in range(numberOfCookings):
cook(int(sys.argv[2+i]))
Upvotes: 1