The subprocess module in Python is used to spawn new processes, connect to their inputs/outputs/errors pipes, and obtain their return codes.
Here’s how to use it:
1. Importing the module
```
import subprocess
```
1. Running External commands:
Use the call() function to call external commands.
```
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
```
```
subprocess.call([“ls”, “-l”])
```
1. Communicating with the process:
If you want to send some data to the process’s `stdin` or if you want to get some data from the process’s `stdout` or `stderr`, use the `Popen` function.
```
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
```
```
p = subprocess.Popen([“ls”,”-l”], stdout=subprocess.PIPE)
1. Getting the output as a string:
If you want to get the output of a command as a string, use the `check_output` function.
```
output = subprocess.check_output([“ls”, “-l”])
print(output)
```
Note: If the command you are trying to execute is not in your PATH, you have to provide the full path to the command. Also, keep in mind that all commands might not be available like they are when using a particular shell and that the module doesn’t provide a way of dealing with user interactivity.