Reputation: 551
Using Python, I want to know whether Java is installed.
Upvotes: 6
Views: 7486
Reputation: 29317
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?).
Upvotes: 2
Reputation: 2390
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
Upvotes: 5
Reputation: 718798
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):
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.
Upvotes: 7