我有一个用c语言编写的windows命令行工具,它通过串行usb加密狗扫描蓝牙设备。
它将循环遍历范围内的所有设备,直到收到ctrl+c命令为止。
device1 name firmware
device2 name firmware
device3 name firmware
device1 name firmware
device2 name firmware
device3 name firmware
...
我想在扫描到达某个设备时停止扫描,这样我就可以发出更新固件命令。
此时,我只能捕获Ctrl +C命令后的输出,使用以下函数启动扫描、休眠,然后发出CTRL+C命令,然后捕获错误并处理输出
except
阻止:
command = [self.cli_tool, '-s']
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
stream = []
if self.check_dongle_firmware() is not False:
try:
self.proc = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
startupinfo=startupinfo)
time.sleep(SCAN_TIMEOUT)
os.kill(self.proc.pid, signal.CTRL_C_EVENT)
self.proc.wait()
except KeyboardInterrupt:
for line in self.proc.stdout:
stream.append(line)
for x in stream[7:]:
x = x.decode()
print(x.strip())
我想要这样的东西:
stream = []
self.proc = subprocess.Popen(
command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
startupinfo=startupinfo)
for line in self.proc.stdout:
stream.append(line)
if 'device2' in line.decode().split():
os.kill(self.proc.pid, signal.CTRL_C_EVENT)
self.proc.wait()
但这不起作用。它不会一次读取1行,并且永远不会达到CTRL+C事件。
我需要一次读取和处理1行,这样我就可以停止在某个设备上的进程。
目前,它只读取空字节或字符串,具体取决于管道属性。
打印到屏幕(带有启动信息关闭)或保存到文件而不发布CTRL+C将呈现空。
我尝试了各种组合使用:
universal_newlines=True
bufsize=1
self.proc.communicate()[0]
当我使用类似于
ping
我没有问题,完全控制了输出。
我试过类似的东西,但没有什么能满足我的需要。
我想我遗漏了一些显而易见的东西,或者是由于工具没有在C代码中应用flush命令而无法实现?
任何指导或建议都是值得赞赏的!
在c代码中,fflush只出现在我认为是用于错误处理的以下位置。
project.h
两者都有
bootloader\src\common\
和
receiver\src\common\
//*************************************************************************
//------------------------- assertion of errors --------------------------
//*************************************************************************
/*
* The format is assert(eval, error);
*
* If 'eval' equals 0 then there is an error printed with number 'error'.
*
*/
#define ERR_STACKOVERFLOW 0 // Out of stack space
#define ERR_SCH_OVERFLOW 1 // Scheduler overflow
#define ERR_SCH_OUTRANGE 2 // Scheduler out of range
#define ERR_WSHRS_OUTRANGE 3 // Scheduler out of range
#ifdef __nDEBUG__
#include "./error/error.h"
....
#include <stdio.h>
#define DBG_PRINT(a, args...) { printf(a, ##args);fflush(stdout); }