如何在Lua中实现管道写入后的读取操作?
解决Lua调用PowerShell读写管道的问题
你的代码存在两个核心问题,导致无法实现写入后读取输出的操作,下面是修正后的代码和关键说明:
修正后的代码
local script = [[ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-RestMethod https://raw.githubusercontent.com/MyAcc/MyBranch/main/blabla.lua -Method Get -Headers @{"Authorization" = "Bearer XXXXXXXXXXXXXXXXXXXXXX"} ]] -- 打开双向管道,r+模式支持同时读写 local pipe = io.popen("powershell -command -", "r+") if not pipe then print("无法打开管道") return end -- 向PowerShell写入执行脚本 pipe:write(script) -- 关闭写入端,告知PowerShell输入结束,开始执行脚本 pipe:close("w") -- 读取PowerShell的所有输出结果 local result = pipe:read("*all") pipe:close() print(result)
关键问题说明
错误的句柄赋值
原代码中local pipe = io.popen("powershell -command -","w"):write(script)会把write方法的返回值(而非管道句柄)赋值给pipe,导致后续无法调用:read方法。必须先保存io.popen返回的管道句柄,再单独调用写入操作。管道模式错误
使用"w"模式打开管道只能写入数据,无法读取输出。需要改用"r+"模式创建双向管道,同时支持写入命令和读取执行结果。关闭写入端触发执行
写完脚本后调用pipe:close("w")关闭写入流,PowerShell才会识别到输入已结束,开始执行脚本并输出结果,此时才能读取到正确的返回内容。
额外优化(可选)
如果需要捕获PowerShell的错误信息,可以修改命令将错误输出重定向到标准输出,这样Lua就能读取到错误内容:
local pipe = io.popen("powershell -command \"& { $ErrorActionPreference='Stop'; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-RestMethod https://raw.githubusercontent.com/MyAcc/MyBranch/main/blabla.lua -Method Get -Headers @{'Authorization' = 'Bearer XXXXXXXXXXXXXXXXXXXXXX'} } 2>&1\"", "r") local result = pipe:read("*all") pipe:close() print(result)
这种方式不需要双向写入,直接把脚本嵌入命令行,用"r"模式读取输出即可,适合不需要动态生成脚本的场景。
内容的提问来源于stack exchange,提问作者Retaker
相关产品推荐
相关产品推荐

