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

2024-05-17 06:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在学习使用libvirt模块的python。下面是我编写的一个小脚本,它检查与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


Tags: toimport脚本noneifsysopenconn
2条回答

I found this script here (...)

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

I'm in process of learning python

你做了full official Python tutorial吗?如果没有,那么这就是您真正想要开始的(假设您已经获得了诸如类型、变量、条件、迭代、函数等基本概念,否则您需要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使用一种名为“异常”的机制来表示错误。这比从函数返回错误代码或特殊值更强大、更可用、更可靠

This is all explained in the tutorial,所以我不想麻烦发布更正后的代码,只需遵循教程就足以让您自己修复此代码

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

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

但是,如果要捕获错误,脚本仍需要更改。libvirtapi在出现问题时会引发异常,因此您需要一个try/except块来捕获&;处理它

相关问题 更多 >