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

Raw*_*awr 6 python subprocess popen

test1.py:

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

test1.py输出:

Not running
2

test2.py:

time.sleep(30)
print "done"
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?这不应该归还"还在运行"吗?


由于这里的结果是矛盾的,因此完整的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()]
Run Code Online (Sandbox Code Playgroud)

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

更新输出:

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

Lie*_*yan 7

如果Popen()找不到test2.py,它会生成错误"没有这样的文件或目录",错误号为2. poll()返回此错误号.因为你似乎是通过wsgi运行这个脚本,所以似乎吞噬了你的stderr,你没有看到错误信息:

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

现在,问题可能是因为前端服务器没有将脚本的当前工作目录设置为脚本的目录,请尝试打印os.getcwd()以查看它是否是您所期望的.