如何在Lua脚本中将core.console命令的终端输出保存至TXT文件
解决Lua脚本捕获
core.console输出并保存到TXT文件的方案 方法1:重定向标准输出捕获全部内容
Lua可通过切换标准输出目标,将core.console的所有控制台输出直接写入文件,执行完成后再恢复原有输出流。
代码实现
-- 保存原始标准输出句柄 local original_output = io.output() -- 打开目标文件("w"为覆盖写入,需追加内容则改用"a") local log_file = io.open("em410x_read_result.txt", "w") if not log_file then print("无法打开目标文件") return end -- 将标准输出重定向到文件 io.output(log_file) -- 执行读取命令,所有输出将写入文件 core.console('lf em 410x read') -- 恢复原始标准输出 io.output(original_output) -- 关闭文件 log_file:close()
方法2:自动处理按键交互
如果lf em 410x read命令需要手动按任意键才能继续,上述脚本会卡住。优先尝试给命令加跳过提示的参数(若工具支持):
core.console('lf em 410x read --no-prompt')
若工具不支持该参数,可通过协程模拟回车输入,绕过按键提示:
local original_output = io.output() local log_file = io.open("em410x_read_result.txt", "w") if not log_file then print("无法打开目标文件") return end io.output(log_file) -- 创建协程延迟发送回车,适配命令的按键等待 local co = coroutine.create(function() -- 延迟0.5秒确保命令已弹出提示(Windows环境替换为os.execute("timeout /t 0 /nobreak >nul")) os.execute("sleep 0.5") io.write('\n') end) coroutine.resume(co) core.console('lf em 410x read') io.output(original_output) log_file:close()
验证结果
执行脚本后,打开em410x_read_result.txt即可看到完整输出:
Put the EM4102 tag on the coil PM3 to readPress any key to continue . . .
Read TAG ID:
[+] EM 410x ID B9519AD890
内容的提问来源于stack exchange,提问作者Jarek Barwinski
相关产品推荐
相关产品推荐

