I'm trying to run a sub process on Android (see this question) which requires that the PYTHONHOME environment variable be set. I tried to do so with the following code:
ProcessBuilder pbuilder = new ProcessBuilder("python/bin/python", "test.py");
pbuilder.directory(getFilesDir());
Map<String, String> env = pbuilder.environment();
env.put("PYTHONHOME", "python");
Process process = pbuilder.start();
but I get this exception:
E/AndroidRuntime(25857): FATAL EXCEPTION: main
E/AndroidRuntime(25857): java.lang.UnsupportedOperationException: Can't modify environment
E/AndroidRuntime(25857): at java.lang.SystemEnvironment.put(System.java:740)
E/AndroidRuntime(25857): at java.lang.SystemEnvironment.put(System.java:688)
E/AndroidRuntime(25857): at my code
E/AndroidRuntime(25857): at android.view.View.performClick(View.java:2408)
E/AndroidRuntime(25857): at android.view.View$PerformClick.run(View.java:8816)
E/AndroidRuntime(25857): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(25857): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(25857): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(25857): at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(25857): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(25857): at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(25857): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(25857): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(25857): at dalvik.system.NativeStart.main(Native Method)
Does anyone have any advice? I've tried wrapping the call to python in a shell script which exports PYTHONHOME but that didn't do the trick.
Gabe
Just recently ran into the same problem. Seems like you can't modify the ProcessBuilder's environment map on Android versions <= 2.2. The only workaround that I found was to use exec() rather than the ProcessBuilder. In your case, this would result in something along the lines of:
String[] cmdarray = {"python/bin/python", "test.py"};
String[] envp = {"PYTHONHOME=python"};
Process process = Runtime.getRuntime().exec(cmdarray, envp, getFilesDir());
Hope that helps.
C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With