3

i'm using in my python script:

cmd = ["checkcode.exe", "code=1234"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, close)
result = proc.stdout.readline()

checkcode.exe return a value, or nothing, and stay alive

All works fine when checkcode.exe return a value, but when checkcode.exe don't return value, the script block at result = proc.stdout.readline()

How to resolve the problem?

CDahn
  • 1,795
  • 12
  • 23
Marco T.
  • 57
  • 1
  • 7
  • Is checkcode exiting? If it's not, your readline is waiting for that to happen so it can get an eof marker. – CDahn Jun 14 '14 at 00:48
  • No, checkcode stay alive... – Marco T. Jun 14 '14 at 00:51
  • By 'return a value', do you mean 'writes a value to stdout'? There is a difference between the two. If `checkcode` stays alive, then it cannot return a value, so I assume you do mean that it either writes some data to stdout or it does not. If it does not, then readline is blocked, waiting for some data. – William Pursell Jun 14 '14 at 00:55
  • 3
    Because it's possible that `checkcode` doesn't print anything, but also doesn't exit, it sounds like you're going to need to do a non-blocking read with a timeout. See this question for a way to do that: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python – dano Jun 14 '14 at 00:58
  • checkcode stay alive, but proc.stdout.readline() return a value when checkcode return a value, instead it stay alive. proc.stdout.readline() block (waiting for some data) when checkcode don't return a value. – Marco T. Jun 14 '14 at 00:58
  • @MarcoT. Just to clarify, `checkcode.exe` runs, and sometimes prints something and sometimes doesn't. If you run `checkcode.exe` directly (meaning not via Python), does it exit after it prints (or doesn't print), or does it stay running forever? It's still not clear to me if the "`checkcode.exe` doesn't exit" behavior is expected or not. – dano Jun 14 '14 at 01:02
  • +1 for @dano, I was just going to post that link! – CDahn Jun 14 '14 at 01:04
  • checkcode.exe sometimes prints something sometimes doesn't, but in any case doesn't exit, it stay running forever. – Marco T. Jun 14 '14 at 01:06
  • The asyncproc module seem don't work on windows – Marco T. Jun 14 '14 at 01:08

1 Answers1

4

You must ensure that the subprocess exits in order to prevent readline() from blocking. The readline waits until it receives a newline or end-of-file. EOF is achieved on program exit.

Alternatively, you can use non-blocking I/O as mentioned in the comment above.

CDahn
  • 1,795
  • 12
  • 23