Get java version number from python

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)

Leave a Comment