[英]Using Python how can I extract a version number from a shell output?
I am still learning... 我仍在学习...
Using python I want to extract the version number from a shell output to determine if an upgrade is required. 我想使用python从shell输出中提取版本号,以确定是否需要升级。
I was able to use subprocess.call with shell=true
, however i read this is a security issue and would like some advise on a better method. 我可以将subprocess.call与
shell=true
一起使用,但是我读到这是一个安全问题,希望就更好的方法提供一些建议。 I then hit an AttributeError
as it seems StrictVersion
doesn't see the output as a integer, I think? 然后我碰到了
AttributeError
,因为StrictVersion
似乎没有将输出视为整数,我认为呢?
Here is what I am doing currently. 这是我目前正在做的事情。
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()
I Expect the output of StrictVersion(version) to be 1.2.3
我期望StrictVersion(version)的输出为
1.2.3
but what i get is the below 但是我得到的是下面
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
The immediate and narrow issue is that subprocess.call()
returns exit status (which will be 0
if the grep
didn't fail, or 1
if it did), not output. 直接而狭窄的问题是
subprocess.call()
返回退出状态(如果grep
没有失败,则返回0
,否则,返回1
),而不输出。 This can be worked around by using check_output()
instead: 这可以通过使用
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')
If you want to avoid shell=True
(commendable, but not actually an immediate security issue in your current use case), that might look like: 如果要避免
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.