gpt4 book ai didi

python - 在 Python 中捕获终端输出

转载 作者:太空狗 更新时间:2023-10-30 03:03:24 43 4
gpt4 key购买 nike

我想做一些类似于这里的第二个答案的事情(但不太相似):Simulate Ctrl-C keyboard interrupt in Python while working in Linux

它更简单,我想我只是遗漏了一些东西。比如说,从 python 脚本中,我只想调用“ping”并在第 10 次后终止它。我正在尝试按照上面的链接进行操作:

p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
for line in p.stdout:
print line
if re.search('10', line):
break
os.kill(p.pid, signal.SIGINT)

但它不起作用。

而且我还希望显示“ping”的常规输出。我该怎么做呢?

编辑:这实际上不是我想要执行的“ping”操作。我只是将它用作具有连续输出的命令示例,我想及时终止它。

更具体地说,我正在运行旧版本的 BitTorrent(v5.0.9,来自此处的第三个答案:Where to find BitTorrent source code?),我通过 python 脚本调用它。 bittorrent-console.py 是一个简单的终端版本,因此是“控制台”。它定期输出多行。像这样的东西:

saving:       filename
file size: blah
percent done: 100.0
blah: blahblah

我实际上是这样调用它的:

subprocess.call(['./bittorrent-console.py', 'something.torrent'])

我想在“完成百分比:”中看到它为 100.0 时自动终止它。

编辑:我在 CentOS、Python 2.6 上运行。

最佳答案

首先,您要使用p.stdout.readline。我不确定为什么,但是 for line in p.stdout 似乎没有刷新。也许它被缓冲了。

其次,您应该使用sys.stdout.write(line),因为print 总是附加一些东西。不过,在 Python 3 中,您可以使用 print(line, end="")

此外,您应该更喜欢 p.kill 而不是 os.kill。我不确定您为什么要使用 os.kill

import os
import signal
import subprocess
import sys

p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()

sys.stdout.write(line)
sys.stdout.flush()
if '10' in line:
break

p.kill()

关于python - 在 Python 中捕获终端输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19059294/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com