Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

bash - Get java version number from python

I need to get the java version number, for example "1.5", from python (or bash).

I would use:

os.system('java -version 2>&1 | grep "java version" | cut -d """ -f 2')

But that returns 1.5.0_30

It needs to be compatible if the number changes to "1.10" for example.

I would like to use cut or grep or even sed. It should be in one line.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Java runtime seems to send the version information to the stderr. You can get at this using Python's subprocess module:

>>> import subprocess
>>> version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)

>>> print version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) Client VM (build 24.79-b02, mixed mode)

You can get the version out with a regex:

>>> import re
>>> pattern = '"(d+.d+).*"'

>>> print re.search(pattern, version).groups()[0]
1.7

If you are using a pre-2.7 version of Python, see this question: subprocess.check_output() doesn't seem to exist (Python 2.6.5)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...