[Tutor] Can I set LD_LIBRARY_PATH within a .py file?

Hugo Arts hugo.yoshi at gmail.com
Sun Oct 16 01:22:02 CEST 2011


On Sat, Oct 15, 2011 at 9:51 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> Hello,
> Can I set the LD_LIBRARY_PATH environment variable (on-the-fly) within a .py
> file?
> I would like to use an .so-file that lives in a non-standard location.
>
> This does not work:
> try:
>    os.environ["LD_LIBRARY_PATH"]  += (":" + path)
> except KeyError:
>    os.environ["LD_LIBRARY_PATH"] = path
> Currently, I can only run the program in the terminal:
> export LD_LIBRARY_PATH=/home/dude/Desktop/test
> python /home/dude/Desktop/testLoadLibLinux.py
> This works (yaaayy!), but I'd like to run the .py file directly.
> Is this possible? I also don't  like the fact that I can't test the .py file
> in Idle.
> Perhaps a complicating factor is a bug in LD_LIBRARY_PATH
> in Linux Ubuntu 10 (the version I'm using):
> https://bugs.edge.launchpad.net/ubuntu/+source/xorg/+bug/366728
> https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728/comments/21
> solution:
> sudo gedit /etc/X11/Xsession.options
> (change "use-ssh-agent" into "no-use-ssh-agent")
>
> Thank you in advance for your thoughts!
>
> Cheers!!
> Albert-Jan
>

Alright, I'm not going to pretend to be an expert on this one, a bit
of this is speculation and inference from what I know about dynamic
linking. In short, I don't think you can modify LD_LIBRARY_PATH on the
fly and have it actually work. The reason for this is that the linker
runs and finds all the libraries *before* the python process actually
starts. So by the time you go and modify the environment, all
libraries have already been linked, and your modified variable is
never even read by the linker.

So the best you can do is write a tiny wrapper to set LD_LIBRARY_PATH
and then run your actual script through it. Or you could set the
environment variable and then fork(), I suppose, since the child will
inherit the modified environment. But the wrapper is your simplest
option.

HTH,
Hugo


More information about the Tutor mailing list