2012-08-10 26 views
0

test1.py是subprocess.Popen工作吗?

import cStringIO 
import os 
import cgi 
import time 
import sys 
from subprocess import Popen, PIPE, STDOUT 

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","C:/wamp/www/python/popen/test2.py"], stdout=PIPE, stderr=PIPE) 

    a = 0 
    while a < 10: 
     a += 1 
     print >> output, "%r" % process.returncode 
     print >> output, "%r" % process.poll() 
     print >> output 
     time.sleep(1) 

    while True: 
     out = process.stdout.read(1) 
     if out == '' and process.poll() != None: 
      break 
     if out != '': 
      sys.stdout.write(out) 
      sys.stdout.flush() 

    print >> output, "Output: "+out 

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

test2.py

import cStringIO 
import os 
import cgi 
import time 

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() 

    time.sleep(15) 

    print >> output, "done" 

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

test1.py输出

None 
None 

None 
0 

0 
0 

0 
0 

0 
0 

0 
0 

0 
0 

0 
0 

0 
0 

0 
0 

Output: 

我得到同样的输出是否我设置time.sleep(15) 0秒或30(in test2.py)。有些事情已经结束。此外,我试图读取输出,所以我至少可以告诉它正在读取文件。但我没有输出。这里有什么问题?

回答

2

你的第二个脚本(test2.py)只是定义了一个application功能 - 它不会调用该函数,所以当你运行该脚本没有任何可见的发生。

+0

当我运行在浏览器中它会等待15秒,返回“完成” test2.py – Rawr 2012-08-10 23:33:39

+0

它看起来像你”重新使用像'mod_wsgi'东西来运行该脚本在你的Web服务器WSGI处理程序。当您通过'python'命令行解释器直接运行脚本时,没有什么等价物发生。 – duskwuff 2012-08-10 23:34:29

+0

哦完美!那么如何让脚本正常运行?我应该在代码的最后放置什么才能使其正常运行? – Rawr 2012-08-10 23:39:30

1

要在已经@duskwuff给出了答案扩大......是的子进程工作,就像它应该。

问题是,test2.py脚本几乎立即成功完成,因为从命令shell调用它将运行脚本,但该脚本没有入口点。而且没有办法以你使用它的方式来运行它。 test2.py是一个WSGI应用程序,意味着在某种程度上它会等待连接进来,然后通过你application可调用的请求被运行。

test2.py需要的东西实际上做,可以在命令行中执行:

import time 

def main(): 
    time.sleep(5) 
    print "All done" 

if __name__ == "__main__": 
    main()