Interaction with processes in Python

Running a program

check_output runs the program and returns the output as a binary string, in case execution is successful:

In case of error an exception is raised:

Passing parameters

Parameters can be passed by specifying a list instead of a string. For example to execute ls -l we can do the following:

We cannot pass arguments in a single string unless we specify shell=True, which forces to interpret the string through the shell. However this is dangerous in general.

Popen

Popen executes a program taking input from stdin and sending output to stdout. For example:

Input and output can be made available to the Python program by specifying it as subprocess.PIPE. Then, it is possible to communicate with the process by invoking communicate():

communicate returns a pair corresponding to stdout and stderr (that is not redirected).

Redirecting both input and output

We can also pass data to process via communicate, in the form of a bytestream.

The following example runs cat and sends b'hello'. The effect is to receive as output b'hello' which is the expected behaviour of cat:

Simulating a shell pipeline

We can refer to stdint and stdout of processes so to simulate a shell pipeline.

For example let us simulate ls | grep txt:

Interacting with a process

In order to interact with a program it is possible to use read and write but it is important to observe that:

The following example interacts 10 times with cat:

Exercise

Write a python program that interacts with the following C program and wins the game: