2016-11-21T23:35:33
Running Commands with Python
The Old Way
import os
os.system('find /home/user/documents -type f -iname "*.doc"')
The New, Recommended Way
import subprocess
subprocess.check_call([
'find',
'/home/user/documents',
'-type', 'f',
'-iname', '*.doc'
])
Bonus Tidbit
At this point, we can incorporate some nice exception handling:
import subprocess
try:
subprocess.check_call([
'find',
'/home/user/documents',
'-type', 'f',
'-iname', '*.doc'
])
except subprocess.CallProcessError as e:
print e.returncode
print e.cmd
print e.output
See the official Python Documentation for more usage and recommendations on the subprocess module.