猿问

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

我仍然在学习...


使用 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


慕工程0101907
浏览 240回答 1
1回答

红糖糍粑

直接和狭隘的问题是subprocess.call()返回退出状态(0如果grep没有失败,或者失败1了),而不是输出。这可以通过使用check_output()来解决:version = subprocess.check_output(&nbsp; &nbsp; "ansible --version | awk '/ansible [0-9].[0-9].[0-9]/ { print $2; exit }'", shell=True).strip().decode('utf-8')如果您想避免shell=True(值得称赞,但在您当前的用例中实际上并不是直接的安全问题),这可能如下所示:import reav = subprocess.check_output(['ansible', '--version'])match = re.match('^ansible (\d+[.]\d+[.]\d+)$', av.split(b'\n')[0].decode('utf-8'))if match is None:&nbsp; raise Exception("Unable to get version number from ansible")version = match.group(1)
随时随地看视频慕课网APP

相关分类

Python
我要回答