Python OSError:[Errno 2]

Cae*_*dis 37 python subprocess

我有以下代码试图启动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)
Run Code Online (Sandbox Code Playgroud)

执行代码时,抛出以下异常:

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
Run Code Online (Sandbox Code Playgroud)

我想我错过了一些明显的东西,有人能看出上面的代码有什么问题吗?

sth*_*sth 66

["screen", "-dmS", "RealmD", "top"]而不是["screen -dmS RealmD top"].

也许还可以使用完整的路径screen.

如果程序仍然无法找到,你也可以通过你的shell ["screen", "-dmS", "RealmD", "top"],但是你需要引用并转义你的参数等.如果你打算这样做,请务必阅读文档中信息.

  • 奇怪的是,它不适用于字符串,只有数组. (2认同)

Col*_*ett 9

只有猜测是它无法找到screen.尝试/usr/bin/screen或任何which screen给你的东西.


kir*_*sos 7

问题是您的命令应该拆分.子过程要求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''') 
Run Code Online (Sandbox Code Playgroud)

那不行.如果为子进程提供字符串,则假定这是您要执行的命令的路径.该命令需要是一个列表.查看http://www.gossamer-threads.com/lists/python/python/724330.此外,因为您正在使用文件重定向,所以您应该使用subprocess.call(cmd, shell=True).你也可以使用shlex.