Executing Linux Shell (Bash) Commands Within Python Code
Ever wondered how to run a linux command like say, grep from within python code? It's fairly simple. Consider I have file1.txt with the following lines:
Hello1 World1 Hello2 World2
Now let's say I have to move all the lines from file1.txt that starts with Hello, to file2.txt
Here's the grep command that'll do it:
grep "^Hello" file1.txt > file2.txt
Okay, now how do I execute this inside a python code? Using subprocess:
import subprocess p = subprocess.Popen('grep "^Hello" file1.txt > file2.txt', stdout=subprocess.PIPE,shell=True) p.communicate()
If you don't want to redirect to file2.txt, but rather you want to parse the output of the command within python, then you can do this:
import subprocess p = subprocess.Popen('grep "^Hello" file1.txt', stdout=subprocess.PIPE,shell=True) output, errormsg = p.communicate() #do something with output print output
Also do note that as the docs say:
Warning: Passing shell=True can be a security hazard if combined with untrusted input.

















