无法将字符串保存到variab中

2024-10-02 12:31:42 发布

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

我与HP uCMDB合作从服务器提取数据。在我的python脚本中,我有:

iostat_cmd = client.executeCmd('iostat -En '+disk+'|egrep \'Vendor|Size\'')

它执行iostat并返回:

-bash-3.2$ iostat -En|egrep "Vendor|Size"
Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:  
Size: 8.59GB <8589934080 bytes>

到目前为止还不错,问题就从这里开始。 它不是将其保存为字符串,而是将其保存为“unicode”对象。 从这一点开始,我使用字符串操作和正则表达式模式,但它们都不起作用,我不能剥离任何换行符,我不能使用正则表达式模式进行拆分等等,我甚至不能强制将其转换为字符串。你知道吗

添加带有打印的有问题代码部分:

        iostat_cmd = client.executeCmd('iostat -En '+disk+'|egrep \'Vendor|Size\'')
        iostat_cmd = iostat_cmd.split(r'\s\s+')
        print iostat_cmd
        print type(iostat_cmd)
jvm 3    | [u'Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:      \r\nSize: 8.59GB <8589934080 bytes>']
jvm 3    | <type 'list'>

基本上,我想删除换行符和回车符。然后,我想使用\s\s+regex模式(即2个或更多空格)将字符串拆分为一个列表,然后将值返回给应用程序。请注意,我已经在网上测试了这个模式,它应该可以工作。你知道吗

我也试过这样:

        iostat_cmd = client.executeCmd('iostat -En '+disk+'|egrep \'Vendor|Size\'')
        iostat_cmd = str(iostat_cmd)
        print iostat_cmd
        print type(iostat_cmd)
jvm 3    | Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:  
jvm 3    | Size: 8.59GB <8589934080 bytes>
jvm 3    | <type 'str'>
        iostat_cmd = iostat_cmd.replace(r'\r',' ')
        print iostat_cmd
        print type(iostat_cmd)
jvm 3    | Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:  
jvm 3    | Size: 8.59GB <8589934080 bytes>
jvm 3    | <type 'str'>
        iostat_cmd = iostat_cmd.split(r'\s\s+')
        print iostat_cmd
        print type(iostat_cmd)
jvm 3    | ['Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:    \r\nSize: 8.59GB <8589934080 bytes>']
jvm 3    | <type 'list'>

知道我做错了什么吗?我好像抓不住,我已经这样做了好几年了。它为什么要将字符串保存到unicode对象中,为什么不使用模式拆分字符串,也不使用replace函数删除字符?你知道吗


Tags: no字符串cmdsizetypevirtualserialrevision
1条回答
网友
1楼 · 发布于 2024-10-02 12:31:42

unicode对象没有问题,这里的问题是结构拆分不接受正则表达式,只接受分隔符列表,您需要:

>>> import re
>>> iostat_cmd = u'Vendor: VMware   Product: Virtual disk     Revision: 1.0  Serial No:      \r\nSize: 8.59GB <8589934080 bytes>'
>>> re.split(r'\s\s+', iostat_cmd)
[u'Vendor: VMware', u'Product: Virtual disk', u'Revision: 1.0', u'Serial No:', u'Size: 8.59GB <8589934080 bytes>']

相关问题 更多 >

    热门问题