Categories
Python Answers

How to run an external command asynchronously from Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *