user1164061
user1164061

Reputation: 4342

subprocess call in python to invoke java jar files with JAVA_OPTS

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.

Upvotes: 12

Views: 21997

Answers (2)

andrewdotn
andrewdotn

Reputation: 34813

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)

Upvotes: 14

andersschuller
andersschuller

Reputation: 13907

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'])

Upvotes: 7

Related Questions