java – Comando Python subprocess.check_output


I'm calling a Java program via Python's subprocess.check_output command. It's not working. In this command, I pass a file as a parameter.

Is something wrong with the command below?

import subprocess

def chamaProg(arquivo):
    r = subprocess.check_output(["java -Djava.library.path="C:\Users\Administrator\Documents\NetBeansProjects\SDK_Java_v1.0.0.2_Beta\SDK Java_v1.0.0.2 BETA\Lib" -jar C:\Users\Administrator\Documents\NetBeansProjects\Busca3-N_java\dist\Busca3-N_java.jar",arquivo])
    return r


The right way to invoke subprocess.check_output() or subprocess.Popen() is to pass each command term in an element of the list/array, not creating a long string. You also need to pay attention to the backslashes, they need to be encoded:

r = subprocess.check_output(['java', '-Djava.library.path="C:\\Users\\Administrator\\Documents\\NetBeansProjects\\SDK_Java_v1.0.0.2_Beta\\SDK Java_v1.0.0.2 BETA\\Lib"', '-jar', 'C:\\Users\\Administrator\\Documents\\NetBeansProjects\\Busca3-N_java\\dist\\Busca3-N_java.jar', arquivo])

Less important, but I also always recommend not writing the path to files or directories explicitly, as this assumes you are sure which file system is being used (FAT, NTFS, ext3, HFS). It may be that in your case you are really sure that this code will only run on Windows, running NTFS. Anyway, my suggestion is:

import os
home = os.path.expanduser('~')
java_lib = os.path.join(home, 'Documents', 'NetBeansProjects', 'SDK_Java_v1.0.0.2_Beta', 'SDK Java_v1.0.0.2 BETA', 'Lib')
jar_path = os.path.join(home, 'Documents', 'NetBeansProjects', 'Busca3-N_java', 'dist', 'Busca3-N_java.jar')
r = subprocess.check_output(['java', '-Djava.library.path="{}"'.format(java_lib), '-jar', jar_path, arquivo])
Scroll to Top