2012-08-10 78 views
6

test1.py:Subprocess.poll()错误地返回一个值

process = Popen(["python","test2.py"]) 
time.sleep(3) 

alive = process.poll() 
if alive is None: 
    print "Still running" 
else: 
    print "Not running\r\n" 
    print "%r" % alive 

test1.py输出:

Not running
2

test2.py:

time.sleep(30) 
print "done" 

这是怎么回事?不应该返回“仍在运行”?


由于矛盾的结果,这里的全test1.py代码:

import cStringIO 
import os 
import cgi 
import time 
from subprocess import Popen 

def application(environ, start_response): 
    headers = [] 
    headers.append(('Content-Type', 'text/plain')) 
    write = start_response('200 OK', headers) 

    input = environ['wsgi.input'] 
    output = cStringIO.StringIO() 

    process = Popen(["python","test2.py"]) 
    time.sleep(3) 

    alive = process.poll() 
    if alive is None: 
     print >> output, "Still running" 
    else: 
     print >> output, "Not running\r\n" 
     print >> output, "%r" % alive 

    output.write(input.read(int(environ.get('CONTENT_LENGTH', '0')))) 
    return [output.getvalue()] 

更新test1.py:

process = Popen(["python","C:/wamp/www/python/popen/test2.py"], shell=True) 
    time.sleep(5) 

    alive = process.poll() 
    if alive is None: 
     #print >> output, "%r" % alive 
     print >> output, "Still running" 
    else: 
     print >> output, "Not running" 
     print >> output, "%r" % alive 
     print >> output, "Current working dir : %s" % os.getcwd() 
     print >> output, os.strerror(0) 

更新的输出:

Not running
0
Current working dir : C:\wamp\bin\apache\apache2.2.22
No error

+0

它对我来说工作得很好。我的输出是“仍在运行”。 – RanRag 2012-08-10 12:23:59

+0

da fuq ...那么我有一个新问题。有任何想法吗?我会发布更多的代码...顺便说一句,我认为这很奇怪,因为在我的搜索没有找到“2”作为poll()的结果。 – Rawr 2012-08-10 12:24:58

+0

与RanRag同样的结果,我也得到了“仍在运行”。 – 2012-08-10 12:31:49

回答

7

如果POPEN()无法找到test2.py,它产生的错误 “没有这样的文件或目录”,并将errno 2.该错误号被以投票方式返回()。既然你似乎是贯穿WSGI这个脚本,有些事情似乎要吞你的标准错误,你不会看到错误消息:

$ cat test1.py 
from subprocess import Popen 
import time 

process = Popen(["python","doesnotexist.py"]) 
time.sleep(3) 

alive = process.poll() 
if alive is None: 
    print "Still running" 
else: 
    print "Not running\r\n" 
    print "%r" % alive 
$ python test1.py 
python: can't open file 'doesnotexist.py': [Errno 2] No such file or directory 
Not running 

2 

现在,这个问题可能是因为你的脚本的当前工作目录未被前端服务器设置为脚本目录,请尝试打印os.getcwd()以查看它是否符合您的期望。

+0

我要指出'test2.py'似乎不会导入'time'模块;虽然这也可能是一个错误,这是你的问题更直接的原因 – chepner 2012-08-10 12:42:40

+1

+1,打我输入这个。如果你想找到一个退出代码是什么,你可以尝试''os.strerror()''函数来看看它是否给出了一个有意义的消息:''>> import os >> os.strerror(2 )''给出信息'''没有这样的文件或目录''。 – Blair 2012-08-10 12:49:04

+0

尝试了'http:// localhost:1234/python/popen/test2.py'和'C:\ wamp \ www \ python \ popen \ test2.py'同样的错误... – Rawr 2012-08-10 12:57:40

1

根据this

的2退出状态指示与执行命令的外壳的问题。您是否尝试过直接在shell中运行test2.py以验证它是否存在问题?正如Lie指出的那样,shell可能找不到你要执行的文件,尽管可能会有另一个问题导致它被破坏。