简体   繁体   English

使用os.system时是否有办法捕获RuntimeErrors?

[英]Is there a way to catch RuntimeErrors when using os.system?

I'm writing a tool that sends commands to the CMD for Google Lighthouse and want to catch the error if an URL isn't valid. 我正在编写一个工具,该命令可以将命令发送给Google Lighthouse的CMD,如果URL无效,则想捕获该错误。 What exception would I use? 我会使用什么例外?

I'm currently trying to catch RuntimeError in the Exception when entering an invalid URL. 我目前正在尝试在输入无效的URL时在“异常”中捕获RuntimeError。

try:
    os.system("lighthouse --quiet {} {} {} {} {} --output-path={}/{}.html ".format(DevEmuStr,throttlingVar,CacheStr,presetVar,url,reportlocation,filename))
except RuntimeError:
    print("Please provide a proper URL")

Instead of "Please provide a proper URL" I still get: 我仍然没有得到“请提供正确的URL”的信息:

Runtime error encountered: The URL you have provided appears to be invalid.
LHError: INVALID_URL
at lighthouse (C:\Users\sugar\AppData\Roaming\npm\node_modules\lighthouse\lighthouse-core\index.js:44:11)
at chromeP.then._ (C:\Users\sugar\AppData\Roaming\npm\node_modules\lighthouse\lighthouse-cli\run.js:182:12)
at process._tickCallback (internal/process/next_tick.js:68:7)

And Lighthouse just continues with the next URL 然后Lighthouse继续下一个URL

Is there another error I could catch? 我还能捕捉到另一个错误吗?

Thanks to everyone that tried to help me, I finally found a way to get it. 感谢所有尝试帮助我的人,我终于找到了一种方法。

By adding this: 通过添加以下内容:

lh_url_ok = os.system("lighthouse --quiet {} {} {} {} {} --output-path={}/{}.html ".format(DevEmuStr,throttlingVar,CacheStr,presetVar,url,reportlocation,filename))
if lh_url_ok >0:
    print("Error")

i was able to check if the exit code was above 0 (0=no error) 我能够检查退出代码是否高于0(0 =无错误)

No, there isn't an exception you could catch from Python. 不,您可以从Python中捕获一个例外。

It appears to me that "Runtime error encountered" is output printed out by lighthouse, it isn't an actual Python exception you could catch. 在我看来,“遇到运行时错误”是由灯塔输出的,这不是您可以捕获的实际Python异常。

Python doesn't know anything about what is internally going on in the executable you start with os.system, you can just get the output and an exit code. 对于以os.system开头的可执行文件,Python不了解内部发生了什么,您只需获取输出和退出代码即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM