Python同步运行?一次运行一个可执行文件
尝试使用python控制大量编译的可执行文件,但遇到时间线问题!我需要能够同时运行两个可执行文件,并且能够在启动另一个可执行文件之前“等待”可执行文件。另外,其中一些需要超级用户。以下是我迄今为止:Python同步运行?一次运行一个可执行文件
import os
sudoPassword = "PASS"
executable1 = "EXEC1"
executable2 = "EXEC2"
executable3 = "EXEC3"
filename = "~/Desktop/folder/"
commandA = filename+executable1
commandB = filename+executable2
commandC = filename+executable3
os.system('echo %s | sudo %s; %s' % (sudoPassword, commandA, commandB))
os.system('echo %s | sudo %s' % (sudoPassword, commandC))
print ('DONESIES')
假设使用os.system()等待执行,以完成移动到下一行之前,这应该同时运行EXEC1和EXEC2,之后他们完成运行EXEC3 ... 但它没有。实际上,它甚至在commandB甚至完成之前在shell中打印“DONESIES”... 请帮忙!
您的脚本仍然会按顺序执行所有3个命令。在shell脚本中,分号只是将多条命令放在一行上的一种方式。它没有做任何特别的事情,它只是一个接一个地运行它们。
如果你想从一个Python程序并行运行外部程序,使用subprocess
模块:https://docs.python.org/2/library/subprocess.html
语法错误,我不应该在'os.system'和'('echo ...'之间有'=',这已经被更新过了 – ovadaflame 2014-11-21 18:26:15
我关于顺序执行的观点仍然存在,请阅读' subprocess.Popen'。 – 2014-11-21 18:33:56
使用subprocess.Popen到在后台运行多个命令。如果你只是想让程序的stdout/err进入屏幕(或者完全抛弃),那么它很简单。如果你想处理命令的输出......变得更加复杂。你可能会为每个命令启动一个线程。
但这里是符合你的情况为例:
import os
import subprocess as subp
sudoPassword = "PASS"
executable1 = "EXEC1"
executable2 = "EXEC2"
executable3 = "EXEC3"
filename = os.path.expanduser("~/Desktop/folder/")
commandA = os.path.join(filename, executable1)
commandB = os.path.join(filename, executable2)
commandC = os.path.join(filename, executable3)
def sudo_cmd(cmd, password):
p = subp.Popen(['sudo', '-S'] + cmd, stdin=subp.PIPE)
p.stdin.write(password + '\n')
p.stdin.close()
return p
# run A and B in parallel
exec_A = sudo_cmd([commandA], sudoPassword)
exec_B = sudo_cmd([commandB], sudoPassword)
# wait for A before starting C
exec_A.wait()
exec_C = sudo_cmd([commandC], sudoPassword)
# wait for the stragglers
exec_B.wait()
exec_C.wait()
print ('DONESIES')
你覆盖'os.system'。调用函数而不是分配给它:'os.system('echo%s | sudo%s'%(sudoPassword,commandC))' – utdemir 2014-11-21 18:09:47
using 'from subprocess import call' 不确定我可以用作超级用户。我尝试了以sudo方式运行IDLE,但它不会将 'call()' 中的命令作为sudo进行处理。你能再解释一下吗? – ovadaflame 2014-11-21 18:22:04
你想在被调用的程序的stdout/stderr中发生什么?在屏幕上显示...写入日志文件? – tdelaney 2014-11-21 18:39:29