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

In Python, I want to count the number of lines in an xh-2.txt .

 import subprocess subprocess.call("wc -l xh-2.txt",shell=True) 

But this gives me exit status, not the result of the team.

I know that print os.popen("wc -l xh-2.txt|cut -d' ' -f1").read() will do the job, but popen will depreciate and why use read ()?

What is the best way to invoke a system command inside Python and get its output result, rather than exit state?

+4
source share
2 answers

Use subprocess.check_output () .

Run the command with arguments and return your 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' >>> 
+4
source

You can use a subprocess recipe

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

Source: https://habr.com/ru/post/1396017/


All Articles