Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a system command inside Python and get its output result, not the exit status

Tags:

python

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?

like image 232
CodeFarmer Avatar asked Feb 12 '12 10:02

CodeFarmer


1 Answers

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'
>>>
like image 137
RanRag Avatar answered Sep 30 '22 03:09

RanRag