Change current process environment's LD_LIBRARY_PATH

后端 未结 4 1533
故里飘歌
故里飘歌 2020-11-29 05:33

Is it possible to change environment variables of current process?

More specifically in a python script I want to change LD_LIBRARY_PATH so that on imp

相关标签:
4条回答
  • 2020-11-29 05:36

    The reason

    os.environ["LD_LIBRARY_PATH"] = ...
    

    doesn't work is simple: this environment variable controls behavior of the dynamic loader (ld-linux.so.2 on Linux, ld.so.1 on Solaris), but the loader only looks at LD_LIBRARY_PATH once at process startup. Changing the value of LD_LIBRARY_PATH in the current process after that point has no effect (just as the answer to this question says).

    You do have some options:

    A. If you know that you are going to need xyz.so from /some/path, and control the execution of python script from the start, then simply set LD_LIBRARY_PATH to your liking (after checking that it is not already so set), and re-execute yourself. This is what Java does.

    B. You can import /some/path/xyz.so via its absolute path before importing x.so. When you then import x.so, the loader will discover that it has already loaded xyz.so, and will use the already loaded module instead of searching for it again.

    C. If you build x.so yourself, you can add -Wl,-rpath=/some/path to its link line, and then importing x.so will cause the loader to look for dependent modules in /some/path.

    0 讨论(0)
  • 2020-11-29 05:36

    Based on the answer from Employed Russian, this is what works for me

    oracle_libs = os.environ['ORACLE_HOME']+"/lib/"
    rerun = True
    
    if not 'LD_LIBRARY_PATH' in os.environ:
      os.environ['LD_LIBRARY_PATH'] = ":"+oracle_libs
    elif not oracle_libs in os.environ.get('LD_LIBRARY_PATH'):
      os.environ['LD_LIBRARY_PATH'] += ":"+oracle_libs
    else:
      rerun = False
    
    if rerun:
      os.execve(os.path.realpath(__file__), sys.argv, os.environ)
    
    0 讨论(0)
  • 2020-11-29 05:51

    well, the environment variables are stored in the dictionary os.environ, so if you want to change , you can do

    os.environ["PATH"] = "/usr/bin"
    
    0 讨论(0)
  • 2020-11-29 05:59

    In my experience trying to change the way the loader works for a running Python is very tricky; probably OS/version dependent; may not work. One work-around that might help in some circumstances is to launch a sub-process that changes the environment parameter using a shell script and then launch a new Python using the shell.

    0 讨论(0)
提交回复
热议问题