我仍然在学习...使用 python 我想从 shell 输出中提取版本号以确定是否需要升级。我能够将 subprocess.call 与 一起使用shell=true,但是我读到这是一个安全问题,并且想要一些关于更好方法的建议。然后我打了一个,AttributeError因为它似乎StrictVersion没有将输出视为整数,我想?以下是我目前正在做的事情。import subprocessfrom distutils.version import StrictVersiondef 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 version1.2.3Traceback (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
1 回答

红糖糍粑
TA贡献1815条经验 获得超6个赞
直接和狭隘的问题是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)
添加回答
举报
0/150
提交
取消