Subprocess Management with asyncio

The asyncio library in Python provides powerful tools for creating and managing subprocesses asynchronously. This capability is essential for running external programs concurrently, handling their input and output, and managing their lifecycle efficiently. This page explores the key concepts and techniques for working with subprocesses using asyncio.

Creating Subprocesses

Subprocesses in asyncio can be created using two primary coroutine functions: asyncio.create_subprocess_exec and asyncio.create_subprocess_shell. These functions allow you to run external programs in separate processes and provide a Process instance to interact with them.

Example: Running a Simple Command

To illustrate the basics of creating a subprocess, consider the following example where we run the ls command to list the contents of the current directory:

Listing 13.1 Running a simple command in a subprocess

import asyncio
from asyncio.subprocess import Process
 
async def main():
    process: Process = await asyncio.create_subprocess_exec('ls', '-l')
    print(f'Process pid is: {process.pid}')
    status_code = await process.wait()
    print(f'Status code: {status_code}')
 
asyncio.run(main())

In this example, a Process instance is created to run the ls command with create_subprocess_exec. The process ID is printed, and the wait coroutine is called to wait for the process to finish, returning the subprocess's status code.

Running Subprocesses Concurrently

Asyncio allows you to run multiple subprocesses concurrently. This is achieved by creating tasks for each subprocess and using asyncio.gather to manage them. This approach is particularly useful when dealing with a large number of subprocesses, as it helps avoid system resource contention.

Communicating with Subprocesses

Communication with subprocesses involves handling input and output streams. For simple input scenarios, the communicate method can be used. For more interactive applications, StreamWriter and StreamReader are employed to manage input and output concurrently.

Example: Interactive Subprocess Communication

The following example demonstrates how to interact with a subprocess using StreamWriter and StreamReader:

Listing 13.12 Using the echo application with subprocesses

import asyncio
from asyncio import StreamWriter, StreamReader
from asyncio.subprocess import Process
 
async def consume_and_send(text_list, stdout: StreamReader, stdin: StreamWriter):
    for text in text_list:
        line = await stdout.read(2048)
        print(line)
        stdin.write(text.encode())
        await stdin.drain()
 
async def main():
    program = ['python3', 'listing_13_11.py']
    process: Process = await asyncio.create_subprocess_exec(*program,
                                                            stdout=asyncio
                                                            .subprocess.PIPE,
                                                            stdin=asyncio
                                                            .subprocess.PIPE)
 
    text_input = ['one\n', 'two\n', 'three\n', 'four\n', 'quit\n']
 
    await asyncio.gather(consume_and_send(text_input, process.stdout, process.stdin), process.wait())
 
asyncio.run(main())

In this example, a subprocess is created with both its standard input and output piped. The consume_and_send coroutine reads from the subprocess's output and writes to its input, allowing for interactive communication.

Terminating Subprocesses

Sometimes, it is necessary to terminate a subprocess before it completes. This can be done using the terminate method. The following example demonstrates how to terminate a long-running subprocess:

Listing 13.2 Terminating a subprocess

import asyncio
from asyncio.subprocess import Process
 
async def main():
    process: Process = await asyncio.create_subprocess_exec('sleep', '3')
    print(f'Process pid is: {process.pid}')
    try:
        status_code = await asyncio.wait_for(process.wait(), timeout=1.0)
        print(status_code)
    except asyncio.TimeoutError:
        print('Timed out waiting to finish, terminating...')
        process.terminate()
        status_code = await process.wait()
        print(status_code)
 
asyncio.run(main())

In this example, a subprocess is created to sleep for 3 seconds. However, it is wrapped in a wait_for with a 1-second timeout. If the timeout is reached, a TimeoutError is raised, and the process is terminated.

By leveraging asyncio's subprocess management capabilities, you can efficiently run and manage external programs, handle their input and output, and ensure they are terminated when necessary.

FAQ (Frequently asked questions)