1

For a script I am making, I need a cross-platform way to check:

  1. If java is installed.
  2. What platform the script is running on (eg windows/amd64 or linux/x86)

in python. How could I do both of these.

Edit: The platform module is perfect for number 2, but a way to see just if java is installed not the version would be preferred.

hifkanotiks
  • 5,915
  • 1
  • 17
  • 24

3 Answers3

1
  1. is a duplicate of How to determine whether java is installed on a system through python? for which I agree with the second answer, in particular, that you shouldn't check most likely. You should document your dependency on it, and have your package manager on whatever systems have one install it, and on Windows have your user install it themselves.

  2. The platform module.

Community
  • 1
  • 1
Julian
  • 3,375
  • 16
  • 27
  • +1 checking if java is on your path. -1 platform module - it's usually better to test individual features than to if/elif on the OS. – user1277476 Jul 27 '12 at 20:02
  • Sounds like you disagree on both points then, since I didn't promote checking if java is on the PATH :). As for the platform module, the OP hasn't provided any information as to what he's checking the OS for, so it may or may not be a good idea. Testing is not necessarily possible in any other way for lots of platform specific things. – Julian Jul 27 '12 at 20:05
  • Why would you need an `elif` for each version? You're just checking it outputs something. Again, if you ask me, I'd not check at all. – Julian Jul 27 '12 at 20:50
1

for checking if java is installed you can use

def run_command(command):
    p = subprocess.Popen(command,
    stdout = subprocess.PIPE,
    stderr = subprocess.STDOUT)
    return iter(p.stdout.readline, b'')
out = list(run_command("java -version"))

from vartec at Running shell command and capturing the output

nda
  • 541
  • 7
  • 18
  • `FileNotFoundError: [Errno 2] No such file or directory: 'java -version'`. You either need to use `Popen(..., shell=True)` or separate the command and its parameters into a list. – bugmenot123 Sep 07 '21 at 06:39
-2

I would suggest to simply try and run java -version. A proper installation of java will add it to the path on both Linux and windows (so the java command line can be executed from "anywhere" on the file system).

For example - here is the result when I run

 java -version
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)
Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27