使用Python如何从Shell输出中提取版本号?

bc81

我仍在学习...

我想使用python从shell输出中提取版本号,以确定是否需要升级。

我可以将subprocess.call与一起使用shell=true,但是我读到这是一个安全问题,希望就更好的方法提供一些建议。然后我按了一下,AttributeError因为似乎StrictVersion没有将输出视为整数,我认为呢?

这是我目前正在做的事情。

import subprocess
from distutils.version import StrictVersion


def updateAnsible():
    print 'Checking Ansible version'
    version = subprocess.call("ansible --version | grep 'ansible [0-9].[0-9].[0-9]' | awk '{ print $2 }'", shell=True)

    print version
    if StrictVersion(version) < StrictVersion('2.7.0'):
        print "Need to upgrade"
    else:
        print "Do not need to upgrade"

if __name__ == '__main__':
    updateAnsible()

我期望StrictVersion(version)的输出为 1.2.3

但是我得到的是下面

Checking Ansible version
1.2.3
Traceback (most recent call last):
0
  File "test.py", line 32, in <module>
    updateAnsible()
  File "test.py", line 26, in updateAnsible
    if StrictVersion(version) < StrictVersion('2.6.0'):
  File "python2.7/distutils/version.py", line 140, in __cmp__
    compare = cmp(self.version, other.version)
AttributeError: StrictVersion instance has no attribute 'version'

Process finished with exit code 1
查尔斯·达菲

紧迫而狭窄的问题是subprocess.call()返回退出状态(0如果grep没有失败,1返回退出状态),而不输出。可以使用以下方法解决此问题check_output()

version = subprocess.check_output(
    "ansible --version | awk '/ansible [0-9].[0-9].[0-9]/ { print $2; exit }'", shell=True
).strip().decode('utf-8')

如果要避免shell=True(值得称赞,但实际上不是当前用例中的紧急安全问题),则可能看起来像这样:

import re

av = subprocess.check_output(['ansible', '--version'])
match = re.match('^ansible (\d+[.]\d+[.]\d+)$', av.split(b'\n')[0].decode('utf-8'))
if match is None:
  raise Exception("Unable to get version number from ansible")
version = match.group(1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章