Python OSError: [错误 2]
我有一段代码,目的是在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
我觉得我可能漏掉了什么明显的东西,有人能看出上面的代码有什么问题吗?
6 个回答
7
问题在于你的命令需要分开写。subprocess模块要求命令是一个列表,而不是一个字符串。
subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END
{for (i in a) {print i a[i]}}' 2_lcsorted.txt > 2_locus_2.txt''')
这样写是行不通的。如果你给subprocess一个字符串,它会认为这是你想要执行的命令的路径。命令必须用列表的形式来写。你可以查看一下这个链接:http://www.gossamer-threads.com/lists/python/python/724330。另外,由于你在使用文件重定向,所以应该用 subprocess.call(cmd, shell=True)
。你也可以使用 shlex
。
9
我猜可能是找不到 screen
这个程序。你可以试试用 /usr/bin/screen
这个路径,或者用 which screen
命令看看它给你什么结果。
66
使用 ["screen", "-dmS", "RealmD", "top"]
代替 ["screen -dmS RealmD top"]
。
也可以试着使用 screen
的完整路径。