Rawr
Rawr

Reputation: 2224

Is subprocess.Popen working?

test1.py

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 output

None
None

None
0

0
0

0
0

0
0

0
0

0
0

0
0

0
0

0
0

Output: 

I get the same output whether I set time.sleep(15) to 0 seconds or 30 (in test2.py). Something is up. Also I tried to read the output so I could at least tell it was reading the file. But I get no output. What's going wrong here?

Upvotes: 0

Views: 319

Answers (2)

jdi
jdi

Reputation: 92647

To expand on the answer already given by @duskwuff... yes subprocess is working just as it should.

The problem is that the test2.py script is completing successfully almost instantly, because calling it from a command shell will run the script, yet the script has no entry point. And there is no way to run this in the fashion you are using it. test2.py is a wsgi application and is meant to be run in a way where it will wait for connections to come in, and then pass the request through your application callable.

test2.py needs something to actually do, that can be executed from a command line:

import time

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

if __name__ == "__main__":
    main()

Upvotes: 1

user149341
user149341

Reputation:

Your second script (test2.py) just defines an application function -- it doesn't call that function, so nothing visible happens when you run the script.

Upvotes: 2

Related Questions