0

I am writing a code wherein I am using subprocess.Popen Command to run a script on terminal that will retrieve some results from database . I may get single result from database or more than one result from database based on which I am writing a condition . For this I want to know the no of outputs I am getting from subprocess command. I know that for reading the stdout line by line we use-

proc = subprocess.Popen(["some command"],stdout = subprocess.PIPE,stdin =subprocess.PIPE, shell=True)
for line in proc.stdout.readlines():
 //do whatever stuff you want

But what if I want to count the no of results from stdout from the command. I have tried using

count=len(proc.stdout.readlines())

But it is not working and giving count value =0 even if I am getting output from stdout. Can somebody please tell me how to count the no of outputs you are getting from stdout using some command with subprocess

I want something like below

proc = subprocess.Popen(["some command"],stdout = subprocess.PIPE,stdin =subprocess.PIPE, shell=True)
count = len(proc.stdout.readlines())
if count ==1:
    for line in proc.stdout.readlines():
        // do something
elif count>1
    for line in proc.stdout.readlines():
        // do something

Can somebody please help me with some methodology ??

rikki
  • 431
  • 1
  • 8
  • 18
  • 1
    Once you already read the file with readlines, the second call get nothing since you're already at the end of the file. Save the content of readLines() and call len() and your loops on this copy. – Olf Feb 08 '19 at 14:11
  • can you see whether there are output on screen after calling to print(proc.stdout.readlines())?, glance at https://stackoverflow.com/a/2813530/4990642 – Soner from The Ottoman Empire Feb 08 '19 at 14:11

1 Answers1

1

First readlines go to the end of your file, so the second got nothing to read. Save the result before doing readlines on the stdout.

proc = subprocess.Popen(["ls"],stdout = subprocess.PIPE,stdin =subprocess.PIPE, shell=True)
out = proc.stdout.readlines()
count = len(out)
if count ==1:
    for line in out:
       print (line)
elif count>1:
    for line in out:
        print (line)
Olf
  • 374
  • 1
  • 20