6

测试1.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

test1.py 输出:

Not running
2

测试2.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

4

2 回答 2

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

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

于 2012-08-10T12:41:19.947 回答
1

据此_

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

于 2012-08-10T12:47:35.890 回答