Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 205
jteichert Avatar asked Aug 04 '15 11:08

jteichert


2 Answers

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)

like image 91
Peter Wood Avatar answered Oct 11 '22 18:10

Peter Wood


Considering an output like this:

$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

You can get the version number with awk like this:

$ java -version 2>&1 | awk -F[\"_] 'NR==1{print $2}'
1.8.0

Or, if you just want the first two .-separated digits:

$ java -version 2>&1 | awk -F[\"\.] -v OFS=. 'NR==1{print $2,$3}'
1.8

Here, awk sets the field separator to either " or _ (or .), so that the line is sliced in pieces. Then, it prints the 2nd field on the first line (indicated by NR==1). By setting OFS we indicate what is the output field separator, so that saying print $2, $3 prints the 2nd field followed by the 3rd one with a . in between.

To use it in Python you need to escape properly:

>>> os.system('java -version 2>&1 | awk -F[\\\"_] \'NR==1{print $2}\'')
1.8.0
>>> os.system('java -version 2>&1 | awk -F[\\\"\.] -v OFS=. \'NR==1{print $2,$3}\'')
1.8
like image 30
fedorqui 'SO stop harming' Avatar answered Oct 11 '22 16:10

fedorqui 'SO stop harming'