简体   繁体   English

使用 Python 中的子进程检查 shell 命令的 output

[英]examine output of shell command using subprocess in Python

I'm running a shell command in a Jupyter Notebook using subprocess or os.system() .我正在使用subprocessos.system()在 Jupyter Notebook 中运行 shell 命令。 The actual output is a dump of thousands of lines of code which takes at least a minute to stdout in terminal.实际的 output 是数千行代码的转储,至少需要一分钟才能在终端中输出标准输出。 In my notebook, I just want to know if the output is more than a couple of lines because if it was an error, the output would only be 1 or 2 lines.在我的笔记本中,我只想知道 output 是否超过几行,因为如果是错误,则 output 将只有 1 或 2 行。 What's the best way to check if I'm receiving 20+ lines and then stop the process and move on to the next?检查我是否收到 20 多行然后停止该过程并继续下一个的最佳方法是什么?

you could read line by line using subprocess.Popen and count the lines (redirecting & merging output and error streams, maybe merging is not needed, depends on the process)您可以使用subprocess.Popen逐行读取并计算行数(重定向和合并 output 和错误流,可能不需要合并,取决于过程)

  • If the number of lines exceeds 20, kill the process and break the loop.如果行数超过 20,则终止进程并中断循环。
  • If the loop ends before the number of lines reaches 20, print/handle an error如果循环在行数达到 20 之前结束,则打印/处理错误

code:代码:

p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)


for lineno,line in enumerate(iter(p.stdout.readline, b'')):
    if lineno == 20:
        print("process okay")
        p.kill()
        break
else:
    # too short, break wasn't reached
    print("process failed return code: {}".format(p.wait()))

note that p.poll() is not None can help to figure out if the process has ended prematurely too请注意p.poll() is not None可以帮助确定该过程是否也过早结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM