Python command subprocess.check_output

3

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

Is there 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
    
asked by anonymous 06.05.2015 / 14:53

1 answer

0

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

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 that 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 under 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])
    
22.06.2015 / 22:24