python - 如何将参数列表传递给 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。赞赏。
解决方案
一个非常简单的例子:
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]))
推荐阅读
- python-3.x - 使用 nameko 为 Pysnmp get_request 创建服务时出错--在 ASN.1 模式对象上尝试“nameko_entrypoints”操作
- javascript - 如何优化包含重复值的组合?
- c# - .Net Core 3.0.100-preview6 - API Json 响应总是驼峰式,但我的课程不是
- c# - 显示复选框列表的不同名称
- mathematical-optimization - 如何通过元组从excel中使用n索引来修复读取变量?
- python - 我能够逐行阅读 txt,不确定现在如何搜索并用 X 替换特定字符串
- swift - 为什么不能使用协议(没有关联类型)类型作为类型别名来符合其他协议的关联类型?
- python - 替换列表中的项目
- tkinter - tkinter entry widgter 值在使用主帧交换类的帧之间传递
- xamarin - Xamarin Shell.BackgroundColor 错误