How to execute a Linux command with Python
In this article you will learn how to execute a Linux command with Python, that is, through the code of your program you will execute an external command.
Hey you all programmers, okay? Let’s learn more about Python!
It is perfectly possible to use external commands with our Python scripts
We need to import a library called subprocess, which has methods to help us with this task.
Let’s look at a practical example:
import subprocess # running ls subprocess.run(["ls", "-l"]) # running clear subprocess.run(["clear"]) # running mkdir subprocess.run(["mkdir", "teste"])
Basically we separate the commands and parameters by commas and they will be executed
In addition, the Python documentation itself recommends this alternative to using commands
We have the possibility to do this also with the OS library, but we must choose subprocess
See here, go to the os.system part of the command
According to doc the most powerful subprocess tools to invoke new processes and receive their results
And using subprocess should be preferable for this function.
It is also worth checking the subprocess documentation for more advanced uses of its resources
Documentation is always the most reliable and up-to-date source of information you can find.
In this article we learned how to run Linux command with Python
This is done through the subprocess library, which has specific methods for this purpose.
Furthermore, we saw that the official Python documentation itself prefers the use of subprocess than other forms like os.system
Want to learn more about Python? Click here!