Python OSError:[Errno 2]

问题描述 投票:37回答:6

我有以下代码试图启动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

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

python subprocess
6个回答
66
投票

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

也许还使用screen的完整路径。


9
投票

只有猜测是它找不到screen。尝试/usr/bin/screenwhich screen给你的任何东西。


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

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


2
投票
commands = [ "screen -dmS RealmD top", "screen -DmS RealmD top -d 5" ]
programs = [ subprocess.Popen(c.split()) for c in commands ]

2
投票

当我写这样的时候我得到了同样的错误: -

subprocess.Popen("ls" ,shell = False , stdout = subprocess.PIPE ,stderr = subprocess.PIPE)

当我使shell = True时,问题就解决了。它会起作用

subprocess.Popen("ls" ,shell = False , stdout = subprocess.PIPE ,stderr = subprocess.PIPE, shell=True)


0
投票

以防万一..我也遇到了这个错误,问题是我的文件是在DOS而不是UNIX所以:

 return subprocess.call(lst_exp)

其中lst_exp是一个args列表,其中一个是“未找到”,因为它是在DOS而不是UNIX但抛出的错误是相同的:

File "/var/www/run_verifier.py", line 59, in main
return subprocess.call(lst_exp)
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
© www.soinside.com 2019 - 2024. All rights reserved.