模块需要 运行 两次才能产生结果

Module require to be run two times to produce result

我正在尝试显示系统的输出。但是,我的脚本只有在我 运行 两次时才会产生结果。下面是脚本。在两个地方都使用 subprocess.Popen 不会产生任何输出,与 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

子进程有自己的文件描述符,因此您可以在子进程启动后立即关闭父进程中的文件。

要读取重定向到文件的整个子进程的输出,请等待它退出:

import subprocess

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

如果要在子进程 运行 时使用输出,请使用 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)

这里是 version for older Python versions and links to fix other possible issues

因为子进程打开了一个新的 shell ,所以第一次创建文件和文件并同时写入另一个子进程的输出是不可能的 os .. 所以唯一的解决办法是使用 os。系统..