In Python, I want to count the number of lines in a file
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?
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)
' 1 test.txt\n'
You could use subprocess recipe
from subprocess import Popen, PIPE
Popen("wc -l xh-2.txt", shell=True, stdout=PIPE).communicate()