本文介绍了从Python内部设置LD_LIBRARY_PATH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在运行时设置指定的 在哪里Python查找共享库?

Is there a way to set specify during runtime where Python looks for shared libraries?

我在fontforge_bin中有fontforge.so,并尝试了以下操作

I have fontforge.so located in fontforge_bin and tried the following

os.environ['LD_LIBRARY_PATH']='fontforge_bin'
sys.path.append('fontforge_bin')
import fontforge

并获得

ImportError: fontforge_bin/fontforge.so: cannot open shared object file: No such file or directory

fontforge_bin/fontforge.so上执行ldd会给出以下信息

Doing ldd on fontforge_bin/fontforge.so gives the following

linux-vdso.so.1 =>  (0x00007fff2050c000)
libpthread.so.0 => /lib/libpthread.so.0 (0x00007f10ffdef000)
libc.so.6 => /lib/libc.so.6 (0x00007f10ffa6c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f110022d000)

推荐答案

您的脚本可以在导入模块之前检查环境变量的存在/正确性,如果缺少该变量,则可以在os.environ中对其进行设置,然后再将其设置为os.environ调用 os.execv()使用相同的命令行参数,但更新了一组环境变量.

Your script can check for the existence/properness of the environment variable before you import your module, then set it in os.environ if it is missing, and then call os.execv() to restart the python interpreter using the same command line arguments but an updated set of environment variables.

仅在 任何其他导入(不包括os和sys)之前,建议这样做,因为可能存在模块导入的副作用,例如打开的文件描述符或套接字,这可能很难完全关闭.

This is only advisable before any other imports (other than os and sys), because of potential module-import side-effects, like opened file descriptors or sockets, which may be challenging to close cleanly.

此代码设置LD_LIBRARY_PATH和ORACLE_HOME:

This code sets LD_LIBRARY_PATH and ORACLE_HOME:

#!/usr/bin/python
import os, sys
if 'LD_LIBRARY_PATH' not in os.environ:
    os.environ['LD_LIBRARY_PATH'] = '/usr/lib/oracle/XX.Y/client64/lib'
    os.environ['ORACLE_HOME'] = '/usr/lib/oracle/XX.Y/client64'
    try:
        os.execv(sys.argv[0], sys.argv)
    except Exception, exc:
        print 'Failed re-exec:', exc
        sys.exit(1)
#
# import yourmodule
print 'Success:', os.environ['LD_LIBRARY_PATH']
# your program goes here

将环境变量设置为启动环境的一部分(在父进程或systemd/etc作业文件中)可能更干净.

It's probably cleaner to set that environment variable as part of the starting environment (in the parent process or systemd/etc job file).

这篇关于从Python内部设置LD_LIBRARY_PATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 14:25
查看更多