[英]examine output of shell command using subprocess in Python
I'm running a shell command in a Jupyter Notebook using subprocess
or os.system()
.我正在使用subprocess
或os.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 和错误流,可能不需要合并,取决于过程)
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.