Reputation: 3589
I ran into this issue today, and managed to repeat it with this small stub of script, running with python 2.7.6 on a win7x64 machine, but the issue came up using portable python on various windows platforms in a much larger script
from subprocess import PIPE, Popen
from time import sleep
class Test(object):
def run_cmd(self, cmd, wait=True):
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
if wait:
p.communicate()
return p
else:
return p
def something(self):
p = self.run_cmd('notepad', wait=False)
import pdb; pdb.set_trace()
while not p.poll():
print 'process still running'
sleep(10)
print p.returncode, p.stdout, p.stderr
def somethingelse(self):
p = self.run_cmd('notepad')
print p.returncode, p.stdout, p.stderr
t = Test()
t.somethingelse()
t.something()
What happens is, somethingelse launches a process in the foreground and the python script waits for it to exit and print the return code, stdout and stderr, but in the second call, something, the process is launched, but whether or not you end the process, python stays in the loop. I then added the pdb step and this is the output,
>>> t.something()
> <stdin>(12)something()
(Pdb) print p
<subprocess.Popen object at 0x0000000002D73D68>
(Pdb) p.poll()
*** SyntaxError: SyntaxError('invalid syntax', ('<string>', 1, 1, '.poll()'))
(Pdb)
The poll, instead of returning None while the process is open, and setting/returning the return code when it is done, always returns None, with the additional output only in the debugger. The process is launched and operates as expected. Any idea what I'm doing that is causing the subprocess.poll to return 'invalid syntax'? It's strange, as it does not throw an exception, it just never gets updated to return the return code and any attempt to print p.pid, p.stdin, p.stdout all produce the same error, but again, only in the debugger.
Upvotes: 0
Views: 754
Reputation: 94881
I'm not sure what the SyntaxError
in pdb is about, but this:
while not p.poll():
print 'process still running'
sleep(10)
will enter an infinite loop if the returncode
of p
is 0, which is a good possibility.
Use this instead:
while p.poll() is None:
print 'process still running'
sleep(10)
Upvotes: 1