5

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?

Eric Leschinski
  • 123,728
  • 82
  • 382
  • 321
CodeFarmer
  • 2,326
  • 18
  • 30
  • 1
    possible duplicate http://stackoverflow.com/questions/2101426/parsing-a-stdout-in-python Use Popen instead as described there. And read STDOUT like the top answers do. – Johan Lundberg Feb 12 '12 at 10:11

2 Answers2

5

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'
>>>
RanRag
  • 43,987
  • 34
  • 102
  • 155
  • i just don't want the filename in the output, weird thing is python doc didn't tell me – CodeFarmer Feb 12 '12 at 11:00
  • 2
    filename will be there in the output because it is present when you run `wc -l test.txt` independently in your shell. You can do this `subprocess.check_output(cm).strip().split(' ')[0]` – RanRag Feb 12 '12 at 11:05
2

You could use subprocess recipe

from subprocess import Popen, PIPE
Popen("wc -l xh-2.txt", shell=True, stdout=PIPE).communicate()[0]
ptitpoulpe
  • 656
  • 4
  • 16
  • #method 1 os.system("wc -l xh-2.txt|cut -d' ' -f1 > tmp") print open("tmp","r").readline() #method 2 from subprocess import check_output sts = check_output("wc -l xh-2.txt") print re.compile(r'(\d+) ').search(sts).groups()[0] – CodeFarmer Feb 12 '12 at 11:28