Python subprocess.check_output command

Asked

Viewed 230 times

3

I am calling a program in Java via command subprocess.check_output python. It is not working. In this command I pass a file as parameter.

There’s 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
  • 2

    The problem is probably in quotes. Try using apostrophes as follows: 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])

1 answer

0


The right way to invoke subprocess.check_output() or subprocess.Popen() is passing each term of the command on an element of the list/array, and not creating a long string. You also need to watch 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 importantly, 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 really make sure that this code will only run on Windows by 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])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.