t0mq t0mq - 2 months ago 9
Linux Question

How to automate interactive console applications in Python?

I want to control running process/program by script in Python.
I have a program `linphonec┬┤ (You can install: apt-get install linphonec).
My task is:


  1. Run
    linphonec
    (I'm using subprocess at the moment)

  2. When
    linphonec
    is running it has many commands to control this and I want to e.g use
    proxy list
    (command in
    linphonec
    ).



Simple flow:

test@ubuntu$ > linphonec
linphonec > proxy list


How can I do this?

Answer

There are actually 2 ways to communicate:

Run your program with myprogram.py | linphonec to pass everything you print to linphonec

Use subprocess.Popen with subprocess.PIPE in constructor via keywrod-args for stdin (propably stdout and stderr, too) and then communicate for a single command or use stdin and stdout (stderr) as files

import subprocess
p=subprocess.Popen("linphonec",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    universal_newlines=True) #this is for text communication
p.stdin.write("proxy list\n")
result_first_line=p.stdout.readline()