Many times is necessary that Python interacts with the computer’s operating system where it is running. For example, to have information about the hard drive partitions. For this to happen, you must create an external command, which invokes the information or program that you want, directly from the OS.
In this post, we will show a Python module that allows processes to be created. These processes call external programs outside the code written in Python. It also allows the output of this program to be seen on the screen, and be run as if in a normal shell. This is the subprocess module, which offers several options to run external programs. We will show here two of them:
Python – The call option ()
1 2 |
import subprocess r = subprocess.call ( "echo Hello World" shell =true) |
In order to manipulate the data from this external program, we use the check_output () function. An example using this function in place of call () is shown below:
1 2 3 4 5 |
subprocess.check_output (['Java -Djava.library.path= "C: Users Administrator Documents NetBeansProjects SDK_Java_ v1.0.0.2_Beta SDK Java_v1.0.0.2 BETA Lib" -jar C:UsersAdministratorDocumentsNetBeansProjects Busca3-N_javadistBusca3-N_java.jar',arquivo]) return r |
This example is calling a Java program, whose information will be handled later in Python, being provided by return.
Python – The Popen option ()
1 2 |
import subprocess proc = subprocess.popen ( "Echo Hello World" shell = True, stdout = subprocess.PIPE) .stdout.read () |
These are some of the ways to call an external command in Python. Do you know a different way? Share with us in the comments area below!
If you want to look for more tips, search our videos about Python. Below are some examples:
You can also follow some of our broadcasters who program in Python, as below:
Another cool way to find out interesting things about Python is to access our project page!