简体   繁体   中英

Storing subprocess.call() return value in a variable

Im trying to get the number of lines in the output of ls -l | awk '{print $1}' ls -l | awk '{print $1}' , which is 7 as shown below.

total
drwxrwxr-x
drwxrwxr-x
-rw-rw-r--
-rw-rw-r--
-rw-rw-r--
-rw-r--r--

I tried to store this value in the variable count but when I print count, the value is 0 instead of 7. I don't know why.

import subprocess

count = subprocess.call('ls -l | awk '{print $1}' | wc -l', shell=True)
print count

OUTPUT:

7
0

You can use subprocess.check_ouput as well. It was specifically meant for checking output as the name suggests.

count = subprocess.check_output("ls -l | awk '{print $1}' | wc -l", shell=True)

Subprocess.call does not return stdout so you need to use Popen instead. Here is what you can do .

import subprocess

count = subprocess.Popen("ls -l | awk '{print $1}' | wc -l",stdout = subprocess.PIPE, shell=True)
print(count.stdout.readlines())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM