3

Is there a way to programmatically replace PYTHONPATH ? I should add that I want to run decode.py with spark-submit

I have the following directory structure at some-path:

decode.py
decode2.py
crfsuite/
    crfsuite.py
    _crfsuite.so
    libcqdb-0.12.so
    libcrfsuite-0.12.so

decode.py:

import crfsuite
if __name__ == '__main__':
    tagger = crfsuite.Tagger()

The following command works:

PYTHONPATH=./crfsuite LD_LIBRARY_PATH=./crfsuite python decode.py

Or if I copied crfsuite/crfsuite.py and crfsuite/_crfsuite.so to my local directory (where decode.py exists), then the following also works:

LD_LIBRARY_PATH=./crfsuite python decode.py

Is there a way to programmatically add .py and .so files? I came up with decode2.py:

from ctypes import *
import imp

if __name__ == '__main__':
    cdll.LoadLibrary('<some-path>/crfsuite/_crfsuite.so')
    imp.load_source('crfsuite', '<some-path>/crfsuite/crfsuite.py')
    tagger = crfsuite.Tagger()

Executing:

LD_LIBRARY_PATH=./crfsuite python decode2.py                                

Traceback (most recent call last):
  File "decode2.py", line 6, in <module>
    imp.load_source('crfsuite', '<some-path>/crfsuite/crfsuite.py')
  File "<some-path>/crfsuite/crfsuite.py", line 17, in <module>
    _crfsuite = swig_import_helper()
  File "<some-path>/crfsuite/crfsuite.py", line 16, in swig_import_helper
    return importlib.import_module('_crfsuite')
  File "sw/anaconda2/lib/python2.7/importli/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named _crfsuite
6
  • 2
    have you tried sys.path.add('<some-path>/crfsuite') ? Commented Apr 5, 2017 at 21:32
  • 3
    @Jean-FrançoisFabre it would be append or insert. sys.path is not a set, it is a list. Commented Apr 5, 2017 at 21:35
  • Ah, I should add that I want to run decode.py with spark-submit . Thus the motivation for doing away with PYTHONPATH Commented Apr 5, 2017 at 21:35
  • @PeterWood sorry I meant append of course. sys.path.append('<some-path>/crfsuite') Commented Apr 5, 2017 at 22:05
  • @Jean-FrançoisFabre , would you like to rewrite your comment as an answer? I can then check it as the accepted answer. Commented Apr 9, 2017 at 15:30

1 Answer 1

3

PYTHONPATH env. variable contents is copied in sys.path module, so before importing you can add some paths like this for instance:

import sys
sys.path.append("/path/to/your/module")
# your_module.py will now be found in /path/to/your/module
import your_module

note that you can also remove paths using sys.path.remove if PYTHONPATH overrides some system lib and you don't want it to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.