Kristian Dienes
Kristian Dienes

Reputation: 169

Change $JAVA_HOME in python script

I've tried to make a python script to switch between 32bit and 64 bit java but for some reason

os.system('export JAVA_HOME=/usr/java/path') 
os.system('export PATH=$JAVA_HOME/bin:$PATH') 

does nothing, but manually it works. How can I fix this? (BTW, this is running on a Linux system.)

Upvotes: 1

Views: 6258

Answers (3)

Adir Dayan
Adir Dayan

Reputation: 1617

You can chain the commands together - jdk set + script execution like this:

setJdk4Gradle = 'export JAVA_HOME=/home/jdkPath && export PATH=$JAVA_HOME/bin:$PATH'
os.system(setJdk4Gradle + ' && executeSomething') 

Upvotes: 0

chiastic-security
chiastic-security

Reputation: 20520

The export line will set an environment variable for the shell in which it's executed and all its sub-shells. But what's happening here is that Python creates a new shell, executes the line to set the environment variable, and then the shell terminates. That means the environment variable is no longer in force. In fact, the JAVA_HOME environment variable you set in the first line isn't even in force for the second line when that gets executed, because that's in its own shell that also terminates immediately!

The way round it is to run a whole shell script that sets the environment variable and then launches Java:

#!/bin/bash

JAVA_HOME=/usr/java/path
PATH=$JAVA_HOME/bin:$PATH

java ...

Upvotes: 2

Andrew Johnson
Andrew Johnson

Reputation: 3186

Environment variables are local to each process. If you want to make a permanent change then you can follow the official java PATH instructions. They recommend adding the export variable command to your .bashrc file.

In ~/.bashrc:

export JAVA_HOME=/usr/java/path
export PATH=$JAVA_HOME/bin:$PATH

Upvotes: 1

Related Questions