How to determine whether java is installed on a system through python?

Question:

Using Python, I want to know whether Java is installed.

Asked By: kush87

||

Answers:

You could use the console commands

>>>import os
>>>os.system("java -version")

java version "1.5.0_19"

or see vartec’s answer at
Running shell command and capturing the output
about storing the output

Answered By: lud0h

There is no 100% reliable / portable way to do this, but the following procedure should give you some confidence that Java has been installed and configured properly (on a Linux):

  1. Check that the “JAVA_HOME” environment variable has been set and that it points to a directory containing a “bin” directory and that the “bin” directory contains an executable “java” command.
  2. Check that the “java” command found via a search of “PATH” is the one that was found in step 1.
  3. Run the “java” command with “-version” to see if the output looks like a normal Java version stamp.

This doesn’t guarantee that the user has not done something weird.

Actually, if it was me, I wouldn’t bother with this. I’d just try to launch the Java app from Python assuming that the “java” on the user’s path was the right one. If there were errors, I’d report them.

Answered By: Stephen C

To check if Java is installed use shutil.which:

import shutil
if shutil.which("java"):
  print("Java is installed on the system")

# Out:
# /usr/bin/java

To get the real path resolving symbolic links use os.path.realpath:

os.path.realpath(shutil.which("java"))

# Out:
# /usr/lib/jvm/java-11-openjdk-amd64/bin/java

To check which version of Java is installed use subprocess.check_output:

from subprocess import check_output, STDOUT

try:
  print(check_output("java -version", stderr=STDOUT, shell=True).decode('utf-8'))
except OSError:
  print("java not found on path")

# Out:
# openjdk version "11.0.16" 2022-07-19
# OpenJDK Runtime Environment (build 11.0.16+8-post-Ubuntu-0ubuntu118.04)
# OpenJDK 64-Bit Server VM (build 11.0.16+8-post-Ubuntu-0ubuntu118.04, mixed mode, sharing)

Notice the stderr=STDOUT (the equivalent of 2>&1). This is because the shell command java -version sends the output to STDERR (see Why does ‘java -version’ go to stderr?).

Answered By: user2314737
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.