How to Execute a Program or Call a System Command in Python
Created
Modified
Using subprocess Module
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. See the following example:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import subprocess
subprocess.run(["ls", "-l"])
... file.txt
On Python 3.4 and earlier, use subprocess.call instead of .run.
Using os.system Method
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations.
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import os
os.system("ls -l")
... file.txt
Using subprocess.Popen Method
Execute a child program in a new process. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import subprocess
out = subprocess.Popen("echo Hello", shell=True, stdout=subprocess.PIPE).stdout.read()
print(out)
b'Hello\n'