In Python, I want to count the number of lines in a file xh-2.txt
.
import subprocess
subprocess.call("wc -l xh-2.txt",shell=True)
But this is giving me exit status, not the result of the command.
I know the command print os.popen("wc -l xh-2.txt|cut -d' ' -f1").read()
will do the job,
but popen is depreciated and why use read()?
What is the best way to call a system command inside Python and get its output result, not exit status?
Use subprocess.check_output().
Run command with arguments and return its output as a byte string.
>>> import subprocess
>>> import shlex
>>> cmd = 'wc -l test.txt'
>>> cm = shlex.split(cmd)
>>> subprocess.check_output(cm,shell=True)
' 1 test.txt\n'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With