TAGS :Viewed: 17 - Published at: a few seconds ago

[ Subprocess wait() function doesn't seem to be waiting for the subprocess to complete ]

I'm trying to run a php script with python's subprocess module.

proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

retCode = proc.wait

print retCode

val = float(kprocess.stdout.read())

return val

I've also tried:

proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

val = float(kprocess.communicate()[0])

return val

Both ways work locally when I just run it in a python interpreter, however when I try to run it on the actual server, I always get "ValueError at / empty string for float()". This leads me to believe that the process is somehow not being waited for. What am I missing?

EDIT: I'm using Django, so it only seems to break when I run with Django.

Answer 1

You have to actually call the processes' wait function:

proc = subprocess.Popen(...)
retCode = proc.wait # retCode will be the function wait
retCode = proc.wait() # retCode will be the return code

However, since you are redirecting the output to, you should heed the warning in the wait docs and use communicate instead. Make sure your code is free of syntactic errors:

  • test.php is probably not a variable name, but a string
  • You're confusing two variable names, proc and kprocess
  • You're blindly parsing the result of communicate (This is not strictly an error, but can hinder error detection and tracing)

Instead, I'd suggest:

proc = subprocess.Popen(['php', '-f', 'test.php'],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()
if proc.returncode != 0:
    raise Exception('Test error: ' + stderr)
return float(stdout)