Reputation: 191
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.
Upvotes: 2
Views: 8331
Reputation: 189357
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.
Upvotes: 2
Reputation: 223
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.
Upvotes: 2