sean read sean read - 26 days ago 13
Python Question

change the priority of pythonpath

When I was loading certain modules [namely pygments.lexers Bash Lexer and pygments.formatters LatexFormatter] I was was getting an error that python couldn't find the modules. I then realised that this problem was being caused by my PYTHONPATH, which is set up for using paraview with python. It brings its own version of pygments, which doesn't work with nbconvert from the jupyter notebook for some reason [Note it is not totally disfunctional, as PythonLexer, and a few others were called without a problem, it was only the ones that I've mentioned above that couldn't be found].

I have a similar problem with mayavi, which wouldn't work with paraview's version of vtk.

Both of these problems can be resolved simply enough by commenting out the python path in the bashrc, but obviously then paraview won't work.

Is there any way to, for example, reduce the priority of the PYTHONPATH so that the system codes in /etc... are called preferentially, but paraview can still find the ones that it needs in the PYTHONPATH?

I am using python 2.76 on linux mint 17.3, paraview is version 4.4.0, installed from source code as per here

Answer

Yes, you can import sys and manipulate sys.path as an ordinary list at runtime. You can rearrange what's there, or just insert at the beginning (sys.path.insert(0, 'path')). Do this before your import statement. If this will cause problems elsewhere, put it back after your import statement.

Note, this is fairly hacky. But it sounds like you might have a case for it, although I have not looked at these specific tools together.

Edit: this is more relevant if you want to control the python path at the level of individual imports within the course of one execution of python. If you want to control the path at the level of one full execution of Python, you can also set the python path on the command line for just that execution like this:

PYTHONPATH=/replacement/path/here python your_script.py

This is more verbose (unless you wrap it in a shell script or alias) than just calling python, but it lets you control the path one script at a time, wheres putting it into .bashrc/.bash_profile or similar changes it for your whole shell session.