简体   繁体   中英

Append path to LD_LIBRARY_PATH in Python

I have been using python3 to set environment variables using os.environ() . I was setting LD_LIBRARY_PATH to a path, which is basically overwriting LD_LIBRARY_PATH using code os.environ["LD_LIBRARY_PATH"] = PATH . But I want to add path using separator : .

I am trying to add path using string concatenation with separator using os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":" + PATH , It doesn't seems to be working like this.

I am getting following error :

os.environ["LD_LIBRARY_PATH"] =os.environ["LD_LIBRARY_PATH"] + ":" + target_directory
 File "/usr/lib/python3.6/os.py", line 669, in __getitem__
  raise KeyError(key) from None
KeyError: 'LD_LIBRARY_PATH'

Let me know what I am doing wrong or what should be done.

The KeyError: 'LD_LIBRARY_PATH' indicates that such key does not exist in your os.environ dictionary. Thus you cannot append anything to the value of a non-existing key.

You should explicitly set a PATH first, then append if you require to do so. I'd suggest you add a check like if PATH not in os.environ().keys() then set it.

Python lets you easily specify a default value.

old = os.environ.get("LD_LIBRARY_PATH")
if old:
    os.environ["LD_LIBRARY_PATH"] = old + ":" + PATH
else:
    os.environ["LD_LIBRARY_PATH"] = PATH

You can accomplish the same with a try / except but it's not really faster or cleaner than this.

The key here is dict.get(value) which unlike dict[value) returns None instead of raising a KeyError . It also allows you to specify a different value than None as its second argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM