Skip to content

How to add an environment variable LD_LIBRARY_PATH to the python code and effective #100567

Not planned
@zjl767864079zjl

Description

@zjl767864079zjl

I add LD_LIBRARY_PATH to the python code like:

test.py

import os
from ctypes import CDLL

os.environ['LD_LIBRARY_PATH'] = "/home/test/myfolder/pyfolder/ztools1226/lib"
print(os.environ)
s_dll_path = f"/home/test/myfolder/pyfolder/ztools1226/lib/libCityPlanParse.so"
dll_load = CDLL(s_dll_path)

I print the os.environ the LD_LIBRARY_PATH value already exists,but when I CDLL /home/test/myfolder/pyfolder/ztools1226/lib/libCityPlanParse.so report an error:
OSError: libCityPlanParse.so: cannot open shared object file: No such file or directory

But when I join in the command-line "export LD_LIBRARY_PATH=/home/test/myfolder/pyfolder/ztools1226/lib" before executing test.py,program execution ok.

So the environment variable I added in the code is not take effect.But I need to do that.How can I write about it to take effect?

My environment

python 3.8.3
Linux system

Activity

avinash-218

avinash-218 commented on Dec 19, 2024

@avinash-218

is there any solution for this issue

duaneg

duaneg commented on May 22, 2025

@duaneg
Contributor

Changes to LD_LIBRARY_PATH will not be effective after the program has started, as dlopen is implemented by the dynamic linker that loads the program, and it reads that environment variable at initial load time. It will not notice subsequent changes (although changes will affect any child processes that inherit the parent's environment).

This is nothing to do with python per se, it is just how Linux (and I assume other POSIX systems) work. The same applies if you use putenv and dlopen from C code, for example. You can work-around it by passing an absolute path to CDLL, setting LD_LIBRARY_PATH prior to running your main code in a wrapper script, and no doubt various other ways.

See here for more explanation: https://stackoverflow.com/questions/856116/changing-ld-library-path-at-runtime-for-ctypes/4326241.

This issue should be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      How to add an environment variable LD_LIBRARY_PATH to the python code and effective · Issue #100567 · python/cpython

      Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

      Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant