Abhay Nayak
Abhay Nayak

Reputation: 1109

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}', 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

Upvotes: 3

Views: 5866

Answers (2)

Mufeed
Mufeed

Reputation: 3208

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)

Upvotes: 3

toheedNiaz
toheedNiaz

Reputation: 1445

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())

Upvotes: 1

Related Questions