0

I am trying to display a output from system . But, my script produces the result only when I run it two times. Below is the script. Using subprocess.Popen at both the places does not produce any out put and same with subprocess.call.

#!/usr/bin/env python
import subprocess
import re
contr = 0
spofchk='su - dasd -c "java -jar /fisc/dasd/bin/srmclient.jar -spof_chk"'
res22 = subprocess.call("touch /tmp/logfile",shell=True,stdout=subprocess.PIPE)
fp = open("/tmp/logfile","r+")
res6 =subprocess.Popen(spofchk,shell=True,stdout=fp)
fil_list=[]
for line in fp:
    line = line.strip()
    fil_list.append(line)
fp.close()
for i in fil_list[2:]:
        if contr % 2 == 0:
            if 'no  SPOF' in i:
                flag=0
                #print(flag)
                #print(i)
            else:
                flag = 1

        else:
            continue
        #Incrementing the counter by 2 so that we will only read line with spof and no SPOF
        contr+=2
shankar
  • 431
  • 7
  • 13
  • Try waiting for the process to complete before reading the file. `res6.wait()` – cdarke Jan 10 '16 at 10:07
  • I tried waiting . I does not work and cause no result to be displayed . One hint is like when i use Popen to create the file and run , in first time it says no file and in second run it produces the output . i tried waiting there also , but no luck. Please help if possible. – shankar Jan 10 '16 at 10:34

2 Answers2

0

The child process has its own file descriptor and therefore you may close the file in the parent as soon as the child process is started.

To read the whole child process' output that is redirected to a file, wait until it exits:

import subprocess

with open('logfile', 'wb', 0) as file:
    subprocess.check_call(command, stdout=file)
with open('logfile') as file:
    # read file here...

If you want to consume the output while the child process is running, use PIPE:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen(command, stdout=PIPE) as process, open('logfile', 'wb') as file:
    for line in process.stdout: # read b'\n'-separated lines
        # handle line...
        # copy it to file
        file.write(line)

Here's a version for older Python versions and links to fix other possible issues.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
-1

Since subprocess open a new shell , so in first time it is not possible to create the file and the file and write the output of another subprocess at the same time .. So only solution for this is to use os. System ..

shankar
  • 431
  • 7
  • 13