How to get around java.lang.UnsupportedOperationException: cannot change environment?

I am trying to run a subprocess on Android (see this question ), which requires setting the PYTHONHOME environment variable. I tried to do this 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 tips? I tried to wrap a python call in a shell script that exports PYTHONHOME, but that does not do the trick.

Gabe

+3
source share
1 answer

More recently, I encountered the same problem. It looks like you cannot change the ProcessBuilder environment map in Android versions <= 2.2. The only workaround I found was to use exec (), not ProcessBuilder. In your case, this will lead to something line by line:

String[] cmdarray = {"python/bin/python", "test.py"};
String[] envp = {"PYTHONHOME=python"};
Process process = Runtime.getRuntime().exec(cmdarray, envp, getFilesDir());

, .

+3

Source: https://habr.com/ru/post/1782927/


All Articles