退出python管道和设置

2024-09-27 23:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下metohd同时读取python脚本的输出并将其写入文件:

FoundError = 0    
def execute(command):    
  with Popen(command, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='',flush=True)
        if 'Error found in job. Going to next' in line:
            FoundError = 1
            break
execute(myCmd)
print(FoundError) --->>this gives a 0 even if I see an error

如果我看到一个特定的错误字符串,我想检查字符串的输出并设置一个变量。在出现错误时,我设置了一个变量以供以后使用,但是这个变量的值变小了。我想在代码的下一部分中使用这个值。 为什么变量会失去它的值


Tags: 文件字符串in脚本trueexecuteifdef
1条回答
网友
1楼 · 发布于 2024-09-27 23:19:35

函数中的FoundError是一个局部变量,它与外部作用域中的FoundError无关

改为从函数返回标志:

def find_error(command):
    ...
    if 'Error found in job. Going to next' in line:
        return True # found error

found_error = find_error(command)
print(found_error)

相关问题 更多 >

    热门问题