执行无效的linux命令时,Lua脚本无法检测捕获错误

执行无效的linux命令时,Lua脚本无法检测捕获错误,第1张

概述我有以下功能,只要我给它一个有效的命令来执行就可以正常工作.只要我给它一个不存在的命令,脚本就会被错误消息中断. #!/usr/bin/luafunction exec_com(com) local ok,res=pcall(function() return io.popen(com) end) if ok then local tmp=res:read('*a 我有以下功能,只要我给它一个有效的命令来执行就可以正常工作.只要我给它一个不存在的命令,脚本就会被错误消息中断.

#!/usr/bin/luafunction 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    endendlocal 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.20sh: zzzz: command not foundExecuted "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脚本无法检测/捕获错误全部内容,希望文章能够帮你解决执行无效的linux命令时,Lua脚本无法检测/捕获错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/1022116.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存