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
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 :(得分:7)
如果Popen()找不到test2.py,它会生成错误“No such file or directory”,错误号为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()以查看它是否是您所期望的。
答案 1 :(得分:1)
根据this
退出状态为2表示执行命令的shell出现问题。您是否尝试直接在shell中运行test2.py
以验证它没有问题?正如Lie指出的那样,shell可能无法找到你想要执行的文件,尽管可能还有另一个问题导致它崩溃。