我有以下功能,只要我给它一个有效的命令来执行就可以正常工作.只要我给它一个不存在的命令,脚本就会被错误消息中断.
#!/usr/bin/lua
function exec_com(com)
local ok,res=pcall(function() return io.popen(com) end)
if ok then
local tmp=res:read('*a')
res:close()
return ok,tmp
else
return ok,res
end
end
local st,val=exec_com('uptime')
print('Executed "uptime" with status:'..tostring(st)..' and value:'..val)
st,val=exec_com('zzzz')
print('Executed "zzzz" with status:'..tostring(st)..' and value:'..val)
当我运行上面的脚本时,我得到以下输出:
Executed "uptime" with status:true and value: 18:07:38 up 1 day, 23:00, 3 users, load average: 0.37, 0.20, 0.20
sh: zzzz: command not found
Executed "zzzz" with status:true and value:
你可以清楚地看到,在执行奇怪的“zzzz”时,pcall()函数仍然报告成功.
有人可以帮助我设法在使用Lua脚本执行不存在或格式错误的Linux命令时捕获异常吗?谢谢.
编辑:在得到pcall()按预期工作的说明后重申了我的请求,问题是由于popen()没有抛出错误.
解决方法:
我使用的方法类似于“临时解决方法”,但它提供了更多信息:
local cmd = "uptime"
local f = io.popen(cmd .. " 2>&1 || echo ::ERROR::", "r")
local text = f:read "*a"
if text:find "::ERROR::" then
-- something went wrong
print("error: " .. text)
else
-- all is fine!!
print(text)
end
标签:linux,lua
来源: https://codeday.me/bug/20190728/1562209.html