English 中文(简体)
如何确定是否通过 p在系统中安装java?
原标题:How to determine whether java is installed on a system through python?
  • 时间:2009-08-26 05:59:12
  •  标签:

我愿利用沙尔来知道是否安装了 Java。

最佳回答

你可以使用独角兽指挥部

>>>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

问题回答

这样做没有100%可靠的/可携带的途径,但以下程序应当使你相信 Java已经安装并适当配置(关于含水层):

  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.

这并不能保证用户没有做过我们所期望的事情。

实际上,如果是我的话,我会这样做。 我只是试图从“ Python”号发射,假定“java”在使用者的道路上是正确的。 如果出现错误,我就报告。

http://docs.python.org/3/library/shutil.html

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

# Out:
# /usr/bin/java

http://docs.python.org/3/library/os.path.htm

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

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

http://docs.python.org/3/library/subprocess.html#subprocess.check_output”rel=“nofollow noreferer”>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)

<代码>stderr=SOUT (相当于2>&1)。 这是因为,单壳指挥系统java -version将产出发送到STDERR(见。 为什么会 j——转而).?





相关问题
热门标签