在celery任务中,执行shell,想要一直获取他的标准输出和标准错误,但是现在line没有值?

在celery任务中,执行shell,想要一直获取他的标准输出和标准错误,但是现在line没有值?

试了几种GPT的答案都不好使!

@app.task
def run_shell(command: str):
    proc = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True
    ) 
    while True:
        stdout_line = proc.stdout.readline()
        stderr_line = proc.stderr.readline()
        if stdout_line:
            print(stdout_line.decode('utf-8').strip())
        if stderr_line:
            print(stderr_line.decode('utf-8').strip())
        if proc.poll() is not None:
            break

要不试一下 我的 ChatGPT plus 版的 答案

参考GPT和自己的思路,您好,您的代码基本正确,但是需要稍作修改才能实现一直获取标准输出和标准错误。具体来说,您需要修改代码中获取输出的方式。subprocess的stdout.readline()和stderr.readline()方法会一直阻塞直到获取到一行完整的输出,如果程序输出的内容没有换行符,那么就会一直阻塞。所以您可以尝试使用stdout.read()和stderr.read()方法,将输出一次性读取完毕,然后再处理每行输出的内容。另外,为了避免程序阻塞,您需要将标准输出和标准错误的读取操作放在两个独立的线程中进行,这样每个线程就可以独立读取输出了。以下是修改后的代码:

import threading

@app.task
def run_shell(command: str):
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
def read_stdout():
while True:
stdout_data = proc.stdout.read(1024)
if not stdout_data:
break
stdout_line = stdout_data.decode('utf-8')
print(stdout_line, end='')
def read_stderr():
while True:
stderr_data = proc.stderr.read(1024)
if not stderr_data:
break
stderr_line = stderr_data.decode('utf-8')
print(stderr_line, end='')
stdout_thread = threading.Thread(target=read_stdout)
stderr_thread = threading.Thread(target=read_stderr)
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()

import subprocess
from celery import Celery

app = Celery('myapp', broker='pyamqp://guest@localhost//')


@app.task
def execute_shell_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = process.communicate()
    return {'stdout': stdout.decode(), 'stderr': stderr.decode()}