-1

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
anonymous
  • 1
  • 1
  • 1

1 Answers1

5

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)
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Thanks for the answer. Sorry about the syntactical issues, I was trying to "paraphrase" my actual code and got mixed up. In any case, the problem seemed to be some path issues with test.php, it's been resolved now. Thanks! – anonymous Jun 16 '11 at 23:48