如何将参数列表传递给 subprocess.run?(python)
How do I pass in a list of arguments to 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]))
我有一个简单的 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]))