3

I know I can get Python to ignore PYTHONPATH if I start it with the -E flag.

But how do I get a script installed by pip to have this flag?

I tried both the "scripts" and the "console_scripts" section of the code and pip strips the -E if I put it on the #! line.

3
  • why would you want this? Shouldn't it up for the target system to decide what its paths are? Commented May 27, 2016 at 20:30
  • I install tools for people, but then they have a PYTHONPATH that includes libraries from another version of Python entirely. So they come back with a stack trace of some function missing from subprocess or another system module. I'd rather have the command "just work" than have to tell them to clean their PYTHONPATH. Life is short. Commented May 28, 2016 at 21:56
  • I see what you mean, but still don't think it should be your problem. All you can do is treat a symptom, and once something changes you need to adjust and treat new symptoms. A clear rule in the docs/your issue tracker and maybe a warning if PYTHONPATH was set is what I would do. If people need those paths they should add a somemodule.pth file in their site-packages. Commented May 30, 2016 at 8:16

2 Answers 2

3

I generally recommend against this sort of trickery. The target system puts paths in place for a reason. If you want to break out of a virtualenv you should simply recommend not installing in a virtualenv in your documentation.

However you can remove the entry from sys.path.

import sys
import os

sys.path = [p for p in sys.path if p not in [os.path.abspath(x) for x in os.environ['PYTHONPATH'].split(':')]]
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't really do it and only works if PYTHONPATH is a single path. I install the tools in a virtualenv. I wish the executables I install only used that virtualenv's include paths.
I have adjusted the answer to work with multiple paths in PYTHONPATH
2

The easiest way right now seems to be to put write a scripts that restarts Python if the flag is not included:

#!/bin/env python
import sys
if not sys.flags.ignore_environment:
      import os
      os.execv(sys.executable, [sys.executable, '-E'] + sys.argv)
# Run your actual script here

Then in setup.py, put this:

setup(..., scripts=['myscript'], ...)

Don't use entry_points/console_scripts. This should not be used for public modules, just for internal scripts.

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.