Menu Close

How to run an external command asynchronously from Python?

Sometimes, we want to run an external command asynchronously from Python.

In this article, we’ll look at how to run an external command asynchronously from Python.

How to run an external command asynchronously from Python?

To run an external command asynchronously from Python, we can use the asyncio.create_subprocess_exec method.

For instance, we write

import asyncio

proc = await asyncio.create_subprocess_exec(
   'ls','-lha',
   stdout=asyncio.subprocess.PIPE,
   stderr=asyncio.subprocess.PIPE)

stdout, stderr = await proc.communicate()

to run a process asynchronously with asyncio.create_subprocess_exec.

We call it with the command and command arguments strings.

And we set stdout and stderr to asyncio.subprocess.PIPE to pipe the results so that we can get their values with proc.communicate.

Using await will keep the code from blocking the CPU from running something else.

Conclusion

To run an external command asynchronously from Python, we can use the asyncio.create_subprocess_exec method.

Posted in Python, Python Answers