为什么 libvirt python 模块会停止我的脚本?

Why libvirt python module stopping my script?

所以,我正在学习 python libvirt 模块。这是我制作的一个小脚本,用于检查是否已成功建立与 libvirtd 的连接并检查一个域。我不是开发人员,我正在走一些捷径,所以我不明白 python 或 libvirt 模块是如何工作的。但我现在真正的问题是,如果未建立连接或未找到域,为什么我的脚本会关闭。

    #!/usr/bin/env python3
    from __future__ import print_function
    import sys
   import libvirt

   domName = 'server1'

   conn = libvirt.open('qemu:///system')
   if conn == None:
        print('Failed to open connection to qemu:///system', file=sys.stderr)
        exit(1)
   else:
        print('Connection opened sucessfully')

   dom = conn.lookupByName(domName)
   if dom == None:
        print('Failed to find the domain '+domName, file=sys.stderr)
        exit(1)
   else:
        print('Domain '+domName+' was found')

   conn.close()
        exit(0)

例如,libvirtd 服务已停止且未建立连接,而是继续向下进入 if 语句,它只是打印一些错误并停止,所以有一个 if 语句应该检查这个,但像这样没有任何功能。看起来像这样

[root@localhost Documents]# ./virt.py 
libvirt: XML-RPC error : Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
Traceback (most recent call last):
  File "./virt.py", line 11, in <module>
    conn = libvirt.open('qemu:///system')
  File "/usr/local/lib64/python3.6/site-packages/libvirt.py", line 277, in open
    if ret is None:raise libvirtError('virConnectOpen() failed')
libvirt.libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
[root@localhost Documents]#  

我设法抑制了错误,但它只是同样的事情,但没有错误。我还找到了这个脚本 here.

libvirt.libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory

此错误消息表明 libvirtd 守护进程实际上 运行 不在此主机上。

如果您想捕获错误,您的脚本仍然需要更改。 libvirt API 会在出现问题时引发异常,因此您不需要根据 "None" 检查 return 值,而是需要一个 try/except 块来捕获并处理它

I found this script here (...)

好吧,那么您已经学到了第一课:您不应该依赖找到的复制粘贴代码 "here"(实际上在大多数其他地方也不应该)。实际上,您可以认为您在网上找到的大约 80% 的代码都是垃圾(我很慷慨)。

I'm in process of learning python

你是不是做了 full official Python tutorial ? If no, then that's really what you want to start with (assuming you already get the basic concepts like types, variables, conditionals, iteration, functions, etc - else you want this

For example libvirtd service is stopped and connection is not established and instead going further down the lines into if statement it just prints some errors and stops

与大多数现代语言一样,Python 使用名为 "exceptions" 的机制来指示错误。这比从函数返回错误代码或特殊值更强大、可用和可靠...

This is all explained in the tutorial,所以我不会费心发布更正的代码,只需按照教程进行操作就足以让您自己修复此代码。