首页 > 解决方案 > 如何将参数列表传递给 subprocess.run?(python)

问题描述

我有一个简单的 def 存储在 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()}')

我的目标是使用子进程库来运行 sample.py,我使用 anaconda 作为我的解释器

import subprocess
path = 'C:/ProgramData/Anaconda3/python.exe C:/Users/admin/Desktop/sample.py'
subprocess.run(path, shell=True)

如何将参数列表传递给 subprocess.run?我尝试使用列表 [cook(1),cook(2),cook(3)] 加入路径。失败。我该怎么办?理想情况下,传入一个列表并一个一个地运行def。赞赏。

标签: pythonshellsubprocess

解决方案


一个非常简单的例子:

subprocess.run(["/path/to/python.exe", "/path/to/sample.py", "2", "3", "4"]) 

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

推荐阅读