0

I'm trying to execute a Java program from within a Python program.

import subprocess
subprocess.run("ls") # ok
subprocess.run("whoami") # ok
subprocess.run("java --version") # not ok

I can run standard shell commands but not the Java executable. Why is that?

Traceback (most recent call last):
  File "syscall.py", line 4, in <module>
    subprocess.run("java --version") # not ok
  File "/usr/lib/python3.6/subprocess.py", line 423, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'java --version': 'java --version'
john-hen
  • 4,410
  • 2
  • 23
  • 40
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    downvoting seems a bit drastic here ... this might be a duplicate, but it is very concise and has a good chance of a google search hit for this topic. Oh well ... – OrenIshShalom May 15 '21 at 11:36

2 Answers2

2

You can't pass complete commands to subprocess.run. It accepts the parsed list of tokens that it uses to start the subprocess.

subprocess.run(["java", "--version"])
subprocess.run(["ls", "-l"])

One way to bypass would be to pass shell=True to run, but that's not recommended.

You can also do the splitting automatically using shlex.split

subprocess.run(shlex.split("java --version"))
rdas
  • 20,604
  • 6
  • 33
  • 46
1

java --version is a shell command, not an executable of its own. You need to pass shell=True.

subprocess.run("java -version", shell=True)

By the way, java uses a single dash for everything, so I changed the command to java -version.

Example output:

>>> import subprocess
>>> subprocess.run("java -version", shell=True)
openjdk version "1.8.0_292"
OpenJDK Runtime Environment (build 1.8.0_292-8u292-b10-0ubuntu1~20.04-b10)
OpenJDK 64-Bit Server VM (build 25.292-b10, mixed mode)
CompletedProcess(args='java -version', returncode=0)
iBug
  • 35,554
  • 7
  • 89
  • 134