1

I am trying to get Python to call a Java program using a command that works when I enter it into the command line.

When I have Python try it with subprocess or os.system, it says:

'java' is not recognized as an internal or external command, operable program or batch file.

From searching, I believe it is because when executing through Python, it will not be able to find java.exe like a normal command would.

Andy Feely
  • 245
  • 1
  • 2
  • 10
  • [this answer describes how the search is performed on Windows](http://stackoverflow.com/a/25167402/4279). What happens if you run `subprocess.check_call('java -version')` or `subprocess.check_call('java -version', shell=True)`? What happens if you run `java -version` from the command-line (`cmd.exe`)? – jfs Aug 01 '15 at 16:13

2 Answers2

0

give absolute path of java location
in my system path is C:\Program Files\Java\jdk1.8.0_45\bin\java.exe

Jameel Grand
  • 2,294
  • 16
  • 32
  • yes if that succeed then try to solve with environment variable. – Jameel Grand Jul 31 '15 at 12:14
  • which os you are using? – Jameel Grand Jul 31 '15 at 12:16
  • first check java command working or not in cmd . if it is ok then try to execute os.getenv('PATH') in python it must be return java lib path. if everithing is ok then it will be complicated problem – Jameel Grand Jul 31 '15 at 12:21
  • @AndyFeely Just to be sure: You have quoted any backslash in that path, especially a '\b' has to be written as '\\b'‽ And when using a shell (`os.system()` or `subprocess` with `shell=True`) you also have to escape space characters. – BlackJack Jul 31 '15 at 14:48
  • How do you get past the space in the program files? – Andy Feely Aug 04 '15 at 08:28
  • I'd skip using an intermediate shell/cmd.exe and use '/' in paths instead of '\'. Then it's: `subprocess.check_call(['C:/Program Files/Java/jdk1.8.0_45/bin/java.exe', '-version'])`. You may have to change the path to your actual Java installation of course. – BlackJack Aug 06 '15 at 13:00
0

You have to set the PATH variable to point to the java location.

import os

os.environ["PATH"] += os.pathsep + os.pathsep.join([java_env])

java_env will be a string containing the directory to java.

(tested on python 3.7)