最近我一直在忙着Popen
。我在后台生成了一个将输出写入TemporaryFile
:
f = tempfile.TemporaryFile()
p = subprocess.Popen(["gatttool"], stdin = subprocess.PIPE, stdout = f)
现在它以我通过stdin
向进程发送命令并稍后读取临时文件的方式工作。而且它是非阻塞的,所以我可以执行其他任务。
问题是gatttool
有时会产生一些输出(例如通知)。而且我正在寻找一种方法来读取此输出而不会阻止TemporaryFile
。
我的问题:
1)从TemporaryFile
(50行)读取输出是否安全,并希望subprocess
优雅地等待我读取该数据或终止?
2)是否有一种优雅的方法可以创建一个回调函数,该函数将在TemporaryFile
上的每个事件上调用(而不是每隔一秒运行一次并读取数据)?
答案 0 :(得分:0)
实际上分辨率非常简单。创建pipe
,使用gatttool
输出作为输入。该管道的输出转到thread
,逐行读取该输出,并解析每一行。检查它,它的工作原理。请把这个问题锁定下来。
# Create a pipe. "gatt_in" ins where the "gatttool" will be dumping it's output.
# We read that output from the other end of pipe, "gatt_out"
gatt_out, gatt_in = os.pipe()
gatt_process = subprocess.Popen(["gatttool", "your parametres"], stdin = subprocess.PIPE,
stdout = gatt_in)
现在,每当我想向gatttool
发送命令时,我都这样做:
gatt_process.stdin.write("Some commands\n")
此命令的结果将在gatt_out
中显示。就我而言,这是在另一个线程中处理的。
答案 1 :(得分:0)
要从子进程提供输入/获取输出,您可以使用subprocess.PIPE
:
from subprocess import Popen, PIPE
p = Popen(['gatttool', 'arg 1', 'arg 2'], stdin=PIPE, stdout=PIPE, bufsize=1)
# provide input
p.stdin.write(b'input data')
p.stdin.close()
# read output incrementally (in "real-time")
for line in iter(p.stdout.readline, b''):
print line,
p.stdout.close()
p.wait()