4

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?

1

2 Answers 2

4

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'
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

i just don't want the filename in the output, weird thing is python doc didn't tell me
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]
2

You could use subprocess recipe

from subprocess import Popen, PIPE
Popen("wc -l xh-2.txt", shell=True, stdout=PIPE).communicate()[0]

1 Comment

#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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.