2012-08-10 76 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可能找不到你要執行的文件,儘管可能會有另一個問題導致它被破壞。