Source code for sitecustomize

"""
Schrodinger specific modifications for python.
"""
# isort: skip_file

import functools
import inspect
import multiprocessing
import os
import pathlib
import socket
import sys
import warnings


# Add directories for DLL dependencies of python modules. This includes
# built-in modules like _ssl.pyd
def add_dll_directories():
    if sys.platform != 'win32':
        return

    # Python <3.8 does PATH style DLL searching and doesn't support
    # the add_dll_directory function
    if (sys.version_info.major == 3) and (sys.version_info.minor < 8):
        return

    if 'SCHRODINGER' not in os.environ:
        return

    s9r = pathlib.Path(os.path.abspath(os.environ['SCHRODINGER']))
    dll_directories = [s9r.joinpath('internal', 'bin')]
    dll_directories += list(s9r.glob('*/bin/Windows-x64'))

    for dll_dir in dll_directories:
        os.add_dll_directory(dll_dir)


add_dll_directories()

# These imports need to happen after add_dll_directories
import ssl  # isort:skip
import urllib.request  # isort:skip
from urllib.request import urlopen as unpatched_urlopen  # isort:skip


# BLDMGR-4113: Monkey-patch urlopen to avoid SSL verification due to
# proliferation of MITM setups at customers
def _urlopen(url,
             data=None,
             timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
             *,
             cafile=None,
             capath=None,
             cadefault=False,
             context=None):
    context = ssl.create_default_context()
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    return unpatched_urlopen(
        url,
        data=data,
        timeout=timeout,
        cafile=None,
        capath=None,
        cadefault=False,
        context=context)


urllib.request.urlopen = _urlopen


class MultiprocessingDisabledMeta(type):

    def __call__(self, *args, **kwargs):
        raise RuntimeError("multiprocessing support is disabled due to "
                           "incompatibilities with Qt")


class MultiprocessingDisabled(metaclass=MultiprocessingDisabledMeta):
    pass


def disable_all_multiprocessing():
    """
    Force all multiprocessing classes and functions to raise an error on use.
    """
    if "SCHRODINGER_ALLOW_UNSAFE_MULTIPROCESSING" in os.environ:
        return
    for attr_name, attr in inspect.getmembers(multiprocessing):
        # allow cpu_count, common and safe function
        if attr_name == "cpu_count":
            continue
        # return an invalid get_start_method, allows numba import
        elif attr_name == "get_start_method":
            setattr(
                multiprocessing, attr_name,
                lambda: "multiprocessing support is disabled due to incompatibilities with Qt"
            )
        # don't reset python modules, only functions and classes
        elif (inspect.isfunction(attr) or inspect.isclass(attr) or
              inspect.ismethod(attr)):
            setattr(multiprocessing, attr_name, MultiprocessingDisabled)


disable_all_multiprocessing()


[docs]def in_dev_env() -> bool: """ Return True if the process is running in a development environment - where SCHRODINGER_SRC or SCHRODINGER_DEV_DEBUG is set. """ schrodinger_src_defined = os.environ.get("SCHRODINGER_SRC", False) schrodinger_dev_debug = os.environ.get("SCHRODINGER_DEV_DEBUG", False) return bool(schrodinger_src_defined) or bool(schrodinger_dev_debug)
# Hide DeprecationWarnings if not in schrodinger dev env (defaults to showing # warnings in __main__) and no -W or PYTHONWARINGS. if not sys.warnoptions: if in_dev_env(): warnings.filterwarnings("default", category=DeprecationWarning) else: warnings.filterwarnings("ignore", category=DeprecationWarning) # remove after BLDMGR-3529 is fixed warnings.filterwarnings( "ignore", message=".*lzma", category=UserWarning, module="pandas.compat") # remove after biopython is updated to 177 # https://github.com/biopython/biopython/commit/ae755750c1c89eaf196a2dbabb2c6b7ffb34da99 warnings.filterwarnings( "ignore", message=".*tree.iter", category=DeprecationWarning, module="Bio.SeqIO.UniprotIO") warnings.filterwarnings( "ignore", message="We intend to remove or replace Bio.Alphabet", category=PendingDeprecationWarning) warnings.filterwarnings( "ignore", message="can't resolve package from __spec__", category=ImportWarning) for _mod in {"past", "tensorflow"}: warnings.filterwarnings( "ignore", message="the imp module", category=DeprecationWarning, module=_mod) # need to upgrade matplotlib to 3.x before python 3.9 warnings.filterwarnings( "ignore", message="PY_SSIZE_T_CLEAN", category=DeprecationWarning, module="matplotlib") warnings.filterwarnings( "ignore", message="Support for multi-dimensional indexing", category=DeprecationWarning, module="matplotlib") # SHARED-7251 warnings.filterwarnings( "ignore", message="an integer is required", category=DeprecationWarning) warnings.filterwarnings( "ignore", message="invalid escape sequence", category=DeprecationWarning, module="past") _import_abc_mods = { "google.protobuf", "jinja2", "markupsafe", "matplotlib", "networkx", "paramiko", "past", "pickleshare", "pyevolve", "pyparsing", "tensorflow", "urllib3", "yaml", } for _mod in _import_abc_mods: warnings.filterwarnings( "ignore", message="Using or importing the ABCs", category=DeprecationWarning, module=_mod) # ignore warnings from tensorflow which we are removing in 20-1 warnings.filterwarnings("ignore", category=FutureWarning, module="tensorboard") warnings.filterwarnings("ignore", category=FutureWarning, module="tensorflow") warnings.filterwarnings("ignore", category=ResourceWarning, module="tensorflow") warnings.filterwarnings( "ignore", message=r".*Script\(\.\.\.\)\.complete\(line, column\)", category=DeprecationWarning, module="jedi.api") warnings.filterwarnings( "ignore", message=r".*get_signatures\(\)\[\.\.\.\]", category=DeprecationWarning, module="jedi.cache") warnings.filterwarnings( "ignore", message=r".*Script\(\.\.\.\)\.complete", category=DeprecationWarning, module="IPython.core.completer") warnings.filterwarnings( "ignore", message=r"path is deprecated", category=DeprecationWarning, module="path") # Syntax warnings due to 3.8 upgrade # Unfortunately, this can't be silenced on a per-module basis, so remove these # when the following have been updated: matminer, matplotlib, mpmath, networkx, # pandas, seaborn, traitlets warnings.filterwarnings( 'ignore', message='"is" with a literal', category=SyntaxWarning) warnings.filterwarnings( 'ignore', message='"is not" with a literal', category=SyntaxWarning) # remove when pip has been updated warnings.filterwarnings( 'ignore', message="'str' object is not callable", category=SyntaxWarning) # MSV-3541 biopython doesn't close file handle reading substitution matrices warnings.filterwarnings( action="ignore", module="Bio.Align.substitution_matrices", lineno=487, category=ResourceWarning) # MSV-3541 use of deprecated subst matrix calls warnings.filterwarnings( action="ignore", module="Bio.SubsMat", message="Bio.SubsMat has been deprecated") warnings.filterwarnings( action="ignore", category=UserWarning, module="torch", message="CUDA initialization: Found no NVIDIA driver on your system.") # PANEL-18170: Monkey-patch requests.get and requests.post to avoid # SSL verification by default since it breaks at customer sites. # Import of requests need to happen after the warning filtering import requests # isort:skip requests.get = functools.partial(requests.get, verify=False) requests.post = functools.partial(requests.post, verify=False)