Python OSError:

我有下面的代码试图启动在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) 

在执行代码时引发以下exception:

 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 

我想我错过了明显的东西,任何人都可以看到上面的代码有什么问题吗?

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

也许还可以使用完整的path来screen

如果程序仍然无法find,你也可以通过shell=True来通过你的shell,但是那么你需要引用和逃避你的参数等。如果你打算这样做,请确保阅读文档中的信息 。

只有猜测是它无法findscreen 。 尝试/usr/bin/screen或任何which screen给你。

问题是你的命令应该被拆分。 子程序要求cmd是一个列表,而不是一个string。 它不应该是:

 subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END {for (i in a) {print ia[i]}}' 2_lcsorted.txt > 2_locus_2.txt''') 

这是行不通的。 如果给subprocess提供一个string,则假定这是要执行的命令的path。 该命令需要是一个列表。 看看http://www.gossamer-threads.com/lists/python/python/724330 。 另外,因为使用文件redirect,所以应该使用subprocess.call(cmd, shell=True) 。 您也可以使用shlex

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

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

  return subprocess.call(lst_exp) 

其中lst_exp是参数列表,其中之一是“找不到”,因为它是在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 

当我这样写时,我得到了同样的错误: –

 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)