简体   繁体   中英

How do I pass in a list of arguments to subprocess.run?(python)

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.

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM