在python下添加环境变量

时间:2012-02-09 09:38:12

标签: python shared-libraries environment-variables ctypes

我正在尝试在python中包含Matlab共享库,如果我首先将以下变量添加到环境变量中,而不是python代码正常工作:

$ export LD_LIBRARY_PATH=/usr/local/MATLAB/R2010b/runtime/glnxa64:/usr/local/MATLAB/R2010b/sys/os/glnxa64:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64/native_threads:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64/server:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64

$ python run.py

run.py的内容

from ctypes import *

if __name__ == '__main__':    

    dll = CDLL("/home/robu/Documents/tmo_compile/libmatrix/distrib/libmatrix.so")

我试图在pythyon中添加这个环境变量

from ctypes import *

import os

LD_LIBRARY_PATH = "/usr/local/MATLAB/R2010b/runtime/glnxa64:/usr/local/MATLAB/R2010b/sys/os/glnxa64:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64/native_threads:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64/server:/usr/local/MATLAB/R2010b/sys/java/jre/glnxa64/jre/lib/amd64"
XAPPLRESDIR = "/usr/local/MATLAB/R2010b/X11/app-defaults"

if __name__ == '__main__':    
    os.environ['LD_LIBRARY_PATH'] =  LD_LIBRARY_PATH
    os.environ['XAPPLRESDIR'] =  XAPPLRESDIR

    print os.environ['LD_LIBRARY_PATH']

    dll = CDLL("/home/robu/Documents/tmo_compile/libmatrix/distrib/libmatrix.so")

但在这种情况下,我得到了错误

OSError: libmwmclmcrrt.so: cannot open shared object file: No such file or directory

我在python中做错了什么?


已更新

我尝试了以下内容:

 if(not os.environ.has_key('LD_LIBRARY_PATH')):
        os.environ['LD_LIBRARY_PATH'] =  LD_LIBRARY_PATH
        os.environ['XAPPLRESDIR'] =  XAPPLRESDIR

        os.execve('run.py', (), os.environ)

但我得到OSError: [Errno 2] No such file or directory

1 个答案:

答案 0 :(得分:2)

首次加载时,加载程序会读取该环境变量。在Python中设置它已经太晚了,因为在Python可执行文件启动时加载了加载器。您需要使用os.exec*()通过运行新的可执行文件来替换当前进程(因此加载新的加载程序)。