Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess call in python to invoke java jar files with JAVA_OPTS

Tags:

java

python

Example code:

import subprocess
subprocess.call(['java', '-jar', 'temp.jar'])

How to specify the JAVA_OPTS in the above command? I am getting a 'java.lang.OutOfMemoryError: unable to create new native thread' when I use the above command and I think specifying JAVA_OPTS in the command would solve the problem.

I did specify the JAVA_OPTS in .bashrc file and it had no effect.

like image 968
user1164061 Avatar asked Feb 07 '13 22:02

user1164061


People also ask

Can we call Java jar from Python?

Using Subprocess module – I found the subprocess as the best way to call any jar from python. Basically, If I say, It is one of the best ways to call any other cross-language package.

How do you call a subprocess in Python?

To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.


2 Answers

There is no need to use JAVA_OPTS - just pass in some more arguments to call(). For example:

import subprocess
subprocess.call(['java', '-jar', 'temp.jar', '-Xmx1024m', '-Xms256m'])
like image 77
andersschuller Avatar answered Nov 15 '22 17:11

andersschuller


You can do this, but finding how to do it in the documentation is kind of a wild goose chase.

The subprocess.call() documentation says,

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the slightly odd notation in the abbreviated signature).

Then the Frequently Used Arguments section, says, at the very end after describing a bunch of other arguments:

These options, along with all of the other options, are described in more detail in the Popen constructor documentation.

Well then! The Popen documentation gives the full signature:

class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

env is the one you want! However, if you just pass env={'JAVA_OPTS': 'foo'}, then that will override all environment variables, including stuff like CLASSPATH, which could break other things. So you probably want to use code like this to add a JAVA_OPTS environment variable for the new process execution, without setting it in the current process:

#!/usr/bin/env python2.7

import os
import subprocess

# Make a copy of the environment    
env = dict(os.environ)
env['JAVA_OPTS'] = 'foo'
subprocess.call(['java', '-jar', 'temp.jar'], env=env)
like image 37
andrewdotn Avatar answered Nov 15 '22 17:11

andrewdotn