osiris81
osiris81

Reputation: 507

how to call an interactive program and show output immediately

I need to call an interactive program in a process and print its output while the process is running. So far, I'm doing it with this function:

def call(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    while True:
        line = process.stdout.readline().rstrip().encode("utf-8")
        if line == '':
            break
    
        print(line)

    process.wait()
    return process.returncode

The problem is, that an interactive program may wait on a user input and does not add a new line after the question, for example:

Authentication realm: ...> ...

Username:

After "Username:", there is no new line and the program expects a user input, so my code does not show "Username:".

Instead of readline() I'd need some functions like bytesavailable and read(size) but there is no such function as bytesavaiable().

Upvotes: 0

Views: 432

Answers (1)

Amber
Amber

Reputation: 526483

Do you need to capture the output of the program for yourself, or do you just need it to be displayed to the user? If it just needs to be displayed, consider just letting the process write it directly to stdout:

process = subprocess.Popen(command, shell=True)

This neatly avoids the need to hack together your own pass-through solution.


If you do need to capture the program output, you can just call .read() without specifying a size. It'll block until it has some data to read (or until the stream is finished, in which case it'll return an empty string), but it won't necessarily wait until the end of a line to return, unlike .readline().

Upvotes: 3

Related Questions