我正在尝试编写一个小程序来连续多次对多台计算机运行可执行文件(delprof2.exe)。我创建了三个包含PC名称的列表,并且基本上需要可执行文件与该列表中的每台机器的switch / c:itroom01(例如)一起运行,但我不知道如何编写代码机器名称部分 - 你可以从reply = 1部分看到我已经走了多远。
参见代码:
import os
import subprocess
itroom = ["itroom01", "itroom02", "itroom03"]
second = ["2nditroom01", "2nditroom02", "2nditroom03"]
csupport = ["csupport-m30", "csupport-m31", "csupport-m32"]
print "Which room's PCs do you want to clear out?"
print "\t(1) = ITRoom"
print "\t(2) = 2nd ITRoom"
print "\t(3) = Curriculum Support"
reply = input("Enter 1, 2 or 3: ")
if reply == 1:
for item in itroom:
subprocess.call(['c:\delprof2\DelProf2.exe /l /c:'%itroom])
raw_input("Press return to continue...")
elif reply == 2:
for item in second:
subprocess.call("c:\delprof2\DelProf2.exe /l")
raw_input("Press return to continue...")
elif reply == 3:
for item in csupport:
subprocess.call("c:\delprof2\DelProf2.exe /l")
raw_input("Press return to continue...")
else:
print "invalid response"
raw_input("Press return to continue...")
非常感谢任何帮助!
谢谢, 克里斯。
答案 0 :(得分:0)
您的问题是字符串格式。阅读the tutorial以了解如何进行基本格式化。
如果所有项都是字符串,则可以连接字符串(+
):
import subprocess
reply = int(raw_input("Enter 1, 2 or 3: "))
for item in [itroom, second, csupport][reply - 1]:
subprocess.check_call([r'c:\delprof2\DelProf2.exe', '/l', '/c:' + item])
注意:如果您希望所有子进程同时运行,那么您可以直接使用Popen
:
import subprocess
reply = int(raw_input("Enter 1, 2 or 3: "))
commands = [[r'c:\delprof2\DelProf2.exe', '/l', '/c:' + item]
for item in [itroom, second, csupport][reply - 1]]
# start child processes in parallel
children = map(subprocess.Popen, commands)
# wait for processes to complete, raise an exception if any of subprocesses fail
for process, cmd in zip(children, commands):
if process.wait() != 0: # failed
raise subprocess.CalledProcessError(process.returncode, cmd)