Collecting grep output via os.system() in Python
Question:
I am trying to use this Ubuntu command on a Linux OS in python
cmd = "grep -n 'str' file.txt"
in the script, im trying to use
command = os.system(cmd)
but when i try to print the variable, it only prints a '0'
, but in the output appears 1:str
. Is there a way to make set this output as a variable?
Answers:
You’re getting 0
because that’s the exit code of the process. Per the documentation for os.system()
:
On Unix, the return value is the exit status of the process
To get the behavior you want, use the subprocess
package instead, like this:
import subprocess
command = subprocess.check_output(cmd, shell=True)
I am trying to use this Ubuntu command on a Linux OS in python
cmd = "grep -n 'str' file.txt"
in the script, im trying to use
command = os.system(cmd)
but when i try to print the variable, it only prints a '0'
, but in the output appears 1:str
. Is there a way to make set this output as a variable?
You’re getting 0
because that’s the exit code of the process. Per the documentation for os.system()
:
On Unix, the return value is the exit status of the process
To get the behavior you want, use the subprocess
package instead, like this:
import subprocess
command = subprocess.check_output(cmd, shell=True)