下面的代码试图在Linux中启动下面的每个“命令”。如果这两个命令中的任何一个因任何原因而崩溃,模块将尝试使它们保持运行。
#!/usr/bin/env python
import subprocess
commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ]
programs = [ subprocess.Popen(c) for c in commands ]
while True:
for i in range(len(programs)):
if programs[i].returncode is None:
continue # still running
else:
# restart this one
programs[i]= subprocess.Popen(commands[i])
time.sleep(1.0)
执行代码时,将引发以下异常:
Traceback (most recent call last):
File "./marp.py", line 82, in <module>
programs = [ subprocess.Popen(c) for c in commands ]
File "/usr/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我想我遗漏了一些显而易见的东西,有人能看出上面的代码有什么问题吗?
问题是你的命令应该被拆分。subcces要求cmd是一个列表,而不是一个字符串。 不应该是:
那不行。如果给子进程一个字符串,则假定这是要执行的命令的路径。命令必须是一个列表。签出http://www.gossamer-threads.com/lists/python/python/724330。另外,因为您使用的是文件重定向,所以应该使用
subprocess.call(cmd, shell=True)
。您也可以使用shlex
。使用
["screen", "-dmS", "RealmD", "top"]
而不是["screen -dmS RealmD top"]
。也可以使用
screen
的完整路径。唯一的猜测是它找不到
screen
。试试/usr/bin/screen
或者which screen
给你的任何东西。相关问题 更多 >
编程相关推荐