Skip to content

Instantly share code, notes, and snippets.

@jobevers
Created January 30, 2018 19:00
Show Gist options
  • Save jobevers/27b9e910e1ac40884c9e0da6fcda87d2 to your computer and use it in GitHub Desktop.
Save jobevers/27b9e910e1ac40884c9e0da6fcda87d2 to your computer and use it in GitHub Desktop.
Ensure venv is first in the path
#! /usr/bin/python
import argparse
import os
import sys
PREPEND = 'prepend'
APPEND = 'append'
SEP = ':'
def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument('where', choices=(PREPEND, APPEND))
parser.add_argument('items')
args = parser.parse_args(args)
items = []
for item in args.items.split(SEP):
item = os.path.abspath(item)
if not os.path.isdir(item):
raise Exception('{} does not exists'.format(item))
items.append(item)
path = os.environ['PATH']
path = path.split(SEP)
output_path = []
# ensure that the virtual environmen is at the front
venv = os.environ.get('VIRTUAL_ENV')
if venv:
output_path.append(os.path.join(venv, 'bin'))
if args.where == PREPEND:
output_path.extend(items)
for item in path:
if item not in output_path:
output_path.append(item)
if args.where == APPEND:
output_path.extend(items)
print(SEP.join(output_path))
if __name__ == '__main__':
sys.exit(main())
@jobevers
Copy link
Author

Can be used in .bashrc to modify path. Its needed because the venv path should always be first, but any prepend actions in bashrc will add to the path. venv's also end up with lots of duplicate paths, this cleans them up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment