【发布时间】:2019-06-05 16:12:29
【问题描述】:
我尝试在 Python 中使用 concurrent.future 多线程和 subprocess.run 来启动外部 Python 脚本。但是我对 subprocess.run() 的 shell=True 部分有一些麻烦。
这是一个外部代码的例子,我们称之为test.py:
#! /usr/bin/env python3
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-x', '--x_nb', required=True, help='the x number')
parser.add_argument('-y', '--y_nb', required=True, help='the y number')
args = parser.parse_args()
print('result is {} when {} multiplied by {}'.format(int(args.x_nb) * int(args.y_nb),
args.x_nb,
args.y_nb))
在我的主要 python 脚本中,我有:
#! /usr/bin/env python3
import subprocess
import concurrent.futures
import threading
...
args_list = []
for i in range(10):
cmd = './test.py -x {} -y 2 '.format(i)
args_list.append(cmd)
# just as an example, this line works fine
subprocess.run(args_list[0], shell=True)
# this multithreading is not working
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(subprocess.run, args_list)
这里的问题是我无法将shell=True 选项传递给executor.map。
我已经试过了,没有成功:
args_list = []
for i in range(10):
cmd = './test.py -x {} -y 2 '.format(i)
args_list.append((cmd, eval('shell=True'))
或
args_list = []
for i in range(10):
cmd = './test.py -x {} -y 2 '.format(i)
args_list.append((cmd, 'shell=True'))
有人知道如何解决这个问题吗?
【问题讨论】:
标签: python-3.x multithreading subprocess concurrent.futures