Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping an interactive command line application in a Python script

I am interested in controlling an interactive CLI application from Python calls.

I guess at the most basic level I need a Python script that will start a CLI application on the host operating system. Pipe anything from standard input to the CLI application, and then pipe any output from the CLI application to standard output.

From this base, it should be pretty straightforward to do some processing on the input and output.

To be honest, I probably just need a pointer on what the technique is called. I have no idea what I need to be searching for.

like image 629
Jack Ryan Avatar asked Oct 14 '09 16:10

Jack Ryan


People also ask

How do you make a Python script interactive?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.

How do you write a Python script and run it using a command prompt?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run an interactive Python shell?

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.


Video Answer


1 Answers

Maybe you want something from Subprocess (MOTW).

I use code like this to make calls out to the shell:

from subprocess import Popen, PIPE

## shell out, prompt
def shell(args, input=''):
    ''' uses subprocess pipes to call out to the shell.

    args:  args to the command
    input:  stdin

    returns stdout, stderr
    '''
    p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(input=input)
    return stdout, stderr
like image 84
Gregg Lind Avatar answered Oct 07 '22 19:10

Gregg Lind