Python操作错误:[Errno 2]

2024-09-24 02:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码试图在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

我想我遗漏了一些显而易见的东西,有人能看出上面的代码有什么问题吗?


Tags: 代码inpy命令forusrtopline
3条回答

问题是你的命令应该被拆分。subcces要求cmd是一个列表,而不是一个字符串。 不应该是:

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

那不行。如果给子进程一个字符串,则假定这是要执行的命令的路径。命令必须是一个列表。签出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给你的任何东西。

相关问题 更多 >