Skip to content

Commit

Permalink
Compatibility with python3 venv module
Browse files Browse the repository at this point in the history
  • Loading branch information
jmfederico committed Mar 16, 2019
1 parent ca201b1 commit 5f8199e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 11 deletions.
1 change: 1 addition & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
The MIT License (MIT)

Copyright (c) 2015 Jan Gosmann
Copyright (c) 2019 Federico Jaramillo

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
Expand Down
68 changes: 57 additions & 11 deletions pylint_venv.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,63 @@
"""
Activate a virtual environment from Python.
Activation logic taken from https://github.com/pypa/virtualenv
"""

import os
import site
import sys


def inithook(venv=None):
def is_venv():
"""Return true if a virtual environment is active."""
return getattr(sys, "base_prefix", sys.prefix) != sys.prefix or hasattr(
sys, "real_prefix"
)


def activate_venv(active_site, venv=None):
"""
Search and activate a Virtual Environment.
Activate the virtual environment from:
- The `venv` param, if one is given.
- `VIRTUAL_ENV` environmental variable if set.
- a `.venv` folder in the current working directory
"""
if venv is None:
venv = os.environ.get('VIRTUAL_ENV', None)
venv = os.environ.get("VIRTUAL_ENV", None)

if venv is None:
cwd = os.getcwd()
exec_path = 'Scripts' if sys.platform == "win32" else 'bin'
if os.path.isfile(os.path.join(cwd, ".venv", exec_path, "activate")):
venv = os.path.join(cwd, ".venv")

if venv is not None:
activate_script = os.path.join(venv, 'bin', 'activate_this.py')
if not os.path.exists(activate_script):
activate_script = os.path.join(venv, 'Scripts', 'activate_this.py')

with open(activate_script, 'r') as f:
source = f.read()
exec(
compile(source, activate_script, 'exec'),
dict(__file__=activate_script))
os.environ["VIRTUAL_ENV"] = venv
os.environ["PATH"] = (
os.path.join(venv, "bin") + os.pathsep + os.environ.get("PATH", "")
)
base = venv
if sys.platform == "win32":
site_packages = os.path.join(base, "Lib", "site-packages")
else:
site_packages = os.path.join(
base, "lib", "python%s" % sys.version[:3], "site-packages"
)

prev = set(sys.path)
active_site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base

# Move the added items to the front of the path, in place
new = list(sys.path)
sys.path[:] = [i for i in new if i not in prev] + [i for i in new if i in prev]


def inithook(venv=None):
"""Activate a Virtual Environment if one is not active."""
if not is_venv():
activate_venv(site, venv)

0 comments on commit 5f8199e

Please sign in to comment.