0

I'm trying to invoke a command line utility from Python. The code is as follows

import subprocess import sys class Executor : def executeEXE(self,executable ) : CREATE_NO_WINDOW = 0x08000000 process = subprocess.Popen(executable, stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW ) while True: line = process.stdout.readline() if line == '' and process.poll() != None: break print line 

The problem with above code is I want the real-time output of above process which I'm not getting. What I'm doing wrong here.

3
  • The way subprocess.popen() output is echoed in this answer might be helpful. Commented Apr 3, 2015 at 13:54
  • Here's another couple of articles that won't help you (it seems you are on Windows). At the very least use iter()-based loop instead of the while-loop. Commented Apr 3, 2015 at 20:27
  • @Sebastian I think the readline() statement is somehow not returning the output. I'm not sure how iter() will help. And yes I'm on Windows. Commented Apr 4, 2015 at 16:41

1 Answer 1

1

there are 2 problems in your code:

  1. first of all, readline() will block untill when a new line is printed out and flushed.
    That means you should execute the code

    while True:
    ...

in a new Thread and call a callback function when the output is ready.

  1. Since the readline is waiting for a new line, you must use

    print 'Hello World'
    sys.stdout.flush()

everytime in your executable.

You can see some code and example on my git:
pyCommunicator

Instead, if your external tool is buffered, the only thing you can try is to use stderr as PIPE: https://stackoverflow.com/a/11902799/2054758

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer :) I understand this problem but I can't find my way out of it. When I run the same executable on command line I can see real time output. And I know it enters newlines. And about second part I've tried that still that doesn't work out. That should mean process is buffering the output. Also if possible can I input commands on stdin of the new process and use it like shell?
yes, just put in your 'executable' variable an array of string command and args
No. I mean literally like shell.. To execute commands on shell, read output and do the same again..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.