Question

I am trying to write a little program to run an executable (delprof2.exe) multiple times in a row against multiple computers. I've created three lists with the PC names in and basically need the executable to run with the switch /c:itroom01 (for example) for each machine in that list, but I don't know how to code the machine name part - you can see from the reply = 1 section how far I've got.

See code:

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...")

Any assistance would be most appreciated!

Thanks, Chris.

Était-ce utile?

La solution

Your issue is with string formatting. Read the tutorial to know how to do the basic formatting.

If all items are strings, you could just concatenate the strings (+):

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

Note: if you want all subprocesses to run concurrently then you could use Popen directly:

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top