Python os.environ.get() Examples

The following are 30 code examples for showing how to use os.environ.get(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os.environ , or try the search function .

Example 1
Project: spleeter   Author: deezer   File: __init__.py    License: MIT License 6 votes vote down vote up
def get(self, model_directory):
        """ Ensures required model is available at given location.

        :param model_directory: Expected model_directory to be available.
        :raise IOError: If model can not be retrieved.
        """
        # Expend model directory if needed.
        if not isabs(model_directory):
            model_directory = join(self.DEFAULT_MODEL_PATH, model_directory)
        # Download it if not exists.
        model_probe = join(model_directory, self.MODEL_PROBE_PATH)
        if not exists(model_probe):
            if not exists(model_directory):
                makedirs(model_directory)
                self.download(
                    model_directory.split(sep)[-1],
                    model_directory)
                self.writeProbe(model_directory)
        return model_directory 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get(this, key, loadfn=None):
	value = None
	if this.values:
	    pair = this.values.get(key)
	    if pair:
		(value, timestamp) = pair
		del this.history[timestamp]
	if value == None:
	    value = loadfn and loadfn()
	if this.values != None:
	    timestamp = this.nextTimestamp
	    this.nextTimestamp = this.nextTimestamp + 1
	    this.values[key] = (value, timestamp)
	    this.history[timestamp] = key
	    if len(this.values) > this.capacity:
		this.removeOldestEntry()
	return value 
Example 3
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get(this, key, loadfn=None):
	value = None
	if this.values:
	    pair = this.values.get(key)
	    if pair:
		(value, timestamp) = pair
		del this.history[timestamp]
	if value == None:
	    value = loadfn and loadfn()
	if this.values != None:
	    timestamp = this.nextTimestamp
	    this.nextTimestamp = this.nextTimestamp + 1
	    this.values[key] = (value, timestamp)
	    this.history[timestamp] = key
	    if len(this.values) > this.capacity:
		this.removeOldestEntry()
	return value 
Example 4
Project: brownie   Author: eth-brownie   File: analyze.py    License: MIT License 6 votes vote down vote up
def get_mythx_client() -> Client:
        """Generate a MythX client instance.

        This method will look for an API key passed as a parameter, and if none
        is found, look for a key in the environment variable :code:`MYTHX_API_KEY`.
        If a key is detected, a PythX client instance is returned, otherwise a
        :code:`ValidationError` is raised.

        :raises: ValidationError if no valid API key is provided
        :return: A PythX client instance
        """

        if CONFIG.argv["api-key"]:
            auth_args = {"api_key": CONFIG.argv["api-key"]}
        elif environ.get("MYTHX_API_KEY"):
            auth_args = {"api_key": environ.get("MYTHX_API_KEY")}
        else:
            raise ValidationError(
                "You must provide a MythX API key via environment variable or the command line"
            )

        return Client(
            **auth_args, middlewares=[ClientToolNameMiddleware(name=f"brownie-{__version__}")]
        ) 
Example 5
Project: pulse2percept   Author: pulse2percept   File: base.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_data_dir(data_dir=None):
    """Return the path of the pulse2percept data directory

    This directory is used to store the datasets retrieved by the data fetch
    utility functions to avoid downloading the data several times.

    By default, this is set to a directory called 'pulse2percept_data' in the
    user home directory.
    Alternatively, it can be set by a ``PULSE2PERCEPT_DATA`` environment
    variable or set programmatically by specifying a path.

    If the directory does not already exist, it is automatically created.

    Parameters
    ----------
    data_dir : str | None
        The path to the pulse2percept data directory.
    """
    if data_dir is None:
        data_dir = environ.get('PULSE2PERCEPT_DATA',
                               join('~', 'pulse2percept_data'))
    data_dir = expanduser(data_dir)
    if not exists(data_dir):
        makedirs(data_dir)
    return data_dir 
Example 6
Project: daudin   Author: terrycojones   File: example-functions.py    License: MIT License 6 votes vote down vote up
def _myPrompt():
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    NORM = '\033[0m'

    cwd = getcwd()
    cwdStr = '%s%s%s ' % (
        GREEN,
        '~' if cwd == environ.get('HOME') else basename(cwd),
        NORM)

    # Note that if git fails to find a repo, it prints to stderr and exits
    # non-zero (both of which we ignore).
    status = run('git symbolic-ref HEAD --short', shell=True,
                 universal_newlines=True, capture_output=True).stdout.strip()
    gitStr = '%s(%s)%s ' % (BLUE, status, NORM) if status else ''

    return '%s%s>>> ' % (cwdStr, gitStr) 
Example 7
Project: cassh   Author: nbeguier   File: cassh_web.py    License: Apache License 2.0 6 votes vote down vote up
def requires_auth(func):
    """ Wrapper which force authentication """
    @wraps(func)
    def decorated(*args, **kwargs):
        """ Authentication wrapper """
        current_user = {}
        current_user['name'] = request.cookies.get('username')
        try:
            current_user['password'] = self_decode(APP.config['ENCRYPTION_KEY'], request.cookies.get('password'))
        except:
            current_user['password'] = 'Unknown'
        current_user['is_authenticated'] = request.cookies.get('last_attempt_error') == 'False'
        if current_user['name'] == 'Unknown' and current_user['password'] == 'Unknown':
            current_user['is_authenticated'] = False
        return func(current_user=current_user, *args, **kwargs)
    return decorated 
Example 8
Project: linter-pylama   Author: AtomLinter   File: main.py    License: MIT License 6 votes vote down vote up
def __init__(self, select=None, ignore=None, params=None):

        params = dict(params.items())
        rcfile = params.get('rcfile', LAMA_RCFILE)
        enable = params.get('enable', None)
        disable = params.get('disable', None)

        if op.exists(HOME_RCFILE):
            rcfile = HOME_RCFILE

        if select:
            enable = select | set(enable.split(",") if enable else [])

        if ignore:
            disable = ignore | set(disable.split(",") if disable else [])

        params.update(dict(
            rcfile=rcfile, enable=enable, disable=disable))

        self.params = dict(
            (name.replace('_', '-'), self.prepare_value(value))
            for name, value in params.items() if value is not None) 
Example 9
Project: galario   Author: mtazzari   File: test_galario.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_FFT(size, real_type, rtol, atol, acc_lib):
    """
    Test the Real to Complex FFTW/cuFFT against numpy Complex to Complex.

    """
    reference_image = create_reference_image(size=size, dtype=real_type)

    ft = np.fft.fft2(reference_image)

    acc_res = acc_lib._fft2d(reference_image)

    # outputs of different shape because np doesn't use the redundancy y[i] == y[n-i] for i>0
    np.testing.assert_equal(ft.shape[0], acc_res.shape[0])
    np.testing.assert_equal(acc_res.shape[1], int(acc_res.shape[0]/2)+1)

    # some real parts can be very close to zero, so we need atol > 0!
    # only get the 0-th and the first half of columns to compare to compact FFTW output
    assert_allclose(unique_part(ft).real, acc_res.real, rtol, atol)
    assert_allclose(unique_part(ft).imag, acc_res.imag, rtol, atol) 
Example 10
Project: dephell   Author: dephell   File: base.py    License: MIT License 6 votes vote down vote up
def _get_locked(self, default_envs: Set[str] = None):
        if 'from' not in self.config:
            python = get_python_env(config=self.config)
            self.logger.debug('choosen python', extra=dict(path=str(python.path)))
            resolver = InstalledConverter().load_resolver(paths=python.lib_paths)
            return self._resolve(resolver=resolver, default_envs=default_envs)

        loader_config = self._get_loader_config_for_lockfile()
        if not Path(loader_config['path']).exists():
            self.logger.error('cannot find dependency file', extra=dict(path=loader_config['path']))
            return None

        self.logger.info('get dependencies', extra=dict(
            format=loader_config['format'],
            path=loader_config['path'],
        ))
        loader = CONVERTERS[loader_config['format']]
        loader = loader.copy(project_path=Path(self.config['project']))
        resolver = loader.load_resolver(path=loader_config['path'])
        attach_deps(resolver=resolver, config=self.config, merge=False)
        return self._resolve(resolver=resolver, default_envs=default_envs) 
Example 11
Project: dephell   Author: dephell   File: base.py    License: MIT License 6 votes vote down vote up
def _resolve(self, resolver, default_envs: Set[str] = None):
        # resolve
        if len(resolver.graph._layers) <= 1:  # if it isn't resolved yet
            self.logger.info('build dependencies graph...')
            resolved = resolver.resolve(silent=self.config['silent'])
            if not resolved:
                conflict = analyze_conflict(resolver=resolver)
                self.logger.warning('conflict was found')
                print(conflict)
                return None

        # apply envs if needed
        if self.config.get('envs'):
            resolver.apply_envs(set(self.config['envs']))
        elif default_envs:
            resolver.apply_envs(default_envs)

        return resolver 
Example 12
Project: dephell   Author: dephell   File: base.py    License: MIT License 6 votes vote down vote up
def _get_loader_config_for_lockfile(self) -> Dict[str, str]:
        # if path specified in CLI, use it
        if set(self.args.__dict__) & {'from', 'from_format', 'from_path'}:
            return self.config['from']

        dumper_config = self.config.get('to')
        if not dumper_config or dumper_config == 'stdout':
            return self.config['from']

        if not Path(dumper_config['path']).exists():
            return self.config['from']

        dumper = CONVERTERS[dumper_config['format']]
        if dumper.lock:
            return dumper_config

        return self.config['from'] 
Example 13
Project: dephell   Author: dephell   File: install.py    License: MIT License 6 votes vote down vote up
def bin_dir(self) -> Path:
        """Global directory from PATH to simlink dephell's binary
        """
        path = Path.home() / '.local' / 'bin'
        if path.exists():
            return path
        paths = [Path(path) for path in environ.get('PATH', '').split(pathsep)]
        for path in paths:
            if path.exists() and '.local' in path.parts:
                return path
        for path in paths:
            if path.exists():
                return path
        raise LookupError('cannot find place to install binary', paths)

    # actions 
Example 14
Project: xenon   Author: Xenon-Bot   File: config.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getattr__(name):
    default = getattr(Config, name, None)
    value = env.get(name.upper())

    if value is not None:
        if isinstance(default, int):
            return int(value)

        if isinstance(default, float):
            return float(value)

        if isinstance(default, bool):
            valid = ["y", "yes", "true"]
            return value.lower() in valid

        if isinstance(default, list):
            return value.split(",")

        return value

    return default 
Example 15
Project: rankeval   Author: hpclab   File: datasets_fetcher.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def __get_data_home__(data_home=None):
    """
    Return the path of the rankeval data dir.
    This folder is used by some large dataset loaders to avoid
    downloading the data several times.
    By default the data dir is set to a folder named 'rankeval_data'
    in the user home folder.
    Alternatively, it can be set by the 'RANKEVAL_DATA' environment
    variable or programmatically by giving an explicit folder path. The
    '~' symbol is expanded to the user home folder.
    If the folder does not already exist, it is automatically created.
    """
    if data_home is None:
        data_home = environ.get('RANKEVAL_DATA', join('~', 'rankeval_data'))
    data_home = expanduser(data_home)
    if not exists(data_home):
        makedirs(data_home)
    return data_home 
Example 16
Project: selene-backend   Author: MycroftAI   File: bootstrap_mycroft_db.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, db_name, user=None):
        db_host = environ.get('DB_HOST', '127.0.0.1')
        db_port = environ.get('DB_PORT', 5432)
        db_ssl_mode = environ.get('DB_SSLMODE')
        if db_name in ('postgres', 'defaultdb', 'mycroft_template'):
            db_user = environ.get('POSTGRES_USER', 'postgres')
            db_password = environ.get('POSTGRES_PASSWORD')
        else:
            db_user = environ.get('DB_USER', 'selene')
            db_password = environ['DB_PASSWORD']

        if user is not None:
            db_user = user

        self.db = connect(
            dbname=db_name,
            user=db_user,
            password=db_password,
            host=db_host,
            port=db_port,
            sslmode=db_ssl_mode
        )
        self.db.autocommit = True 
Example 17
Project: poetry   Author: python-poetry   File: shell.py    License: MIT License 6 votes vote down vote up
def handle(self):
        from poetry.utils.shell import Shell

        # Check if it's already activated or doesn't exist and won't be created
        venv_activated = strtobool(environ.get("POETRY_ACTIVE", "0")) or getattr(
            sys, "real_prefix", sys.prefix
        ) == str(self.env.path)
        if venv_activated:
            self.line(
                "Virtual environment already activated: "
                "<info>{}</>".format(self.env.path)
            )

            return

        self.line("Spawning shell within <info>{}</>".format(self.env.path))

        # Setting this to avoid spawning unnecessary nested shells
        environ["POETRY_ACTIVE"] = "1"
        shell = Shell.get()
        shell.activate(self.env)
        environ.pop("POETRY_ACTIVE") 
Example 18
Project: geemusic   Author: stevenleeg   File: playback.py    License: GNU General Public License v3.0 6 votes vote down vote up
def finished():
    # Scrobble if Last.fm is setup
    if environ.get('LAST_FM_ACTIVE'):
        song_info = queue.current_track()

        if song_info is not None and 'title' in song_info and 'artist' in song_info:
            from ..utils import last_fm

            last_fm.scrobble(
                song_info['title'],
                song_info['artist'],
                environ['LAST_FM_SESSION_KEY']
            )

    queue.next()
    return empty_response()

##
# Intents
# 
Example 19
Project: vnpy_crypto   Author: birforce   File: utils.py    License: MIT License 6 votes vote down vote up
def get_data_home(data_home=None):
    """Return the path of the statsmodels data dir.

    This folder is used by some large dataset loaders to avoid
    downloading the data several times.

    By default the data dir is set to a folder named 'statsmodels_data'
    in the user home folder.

    Alternatively, it can be set by the 'STATSMODELS_DATA' environment
    variable or programatically by giving an explit folder path. The
    '~' symbol is expanded to the user home folder.

    If the folder does not already exist, it is automatically created.
    """
    if data_home is None:
        data_home = environ.get('STATSMODELS_DATA',
                                join('~', 'statsmodels_data'))
    data_home = expanduser(data_home)
    if not exists(data_home):
        makedirs(data_home)
    return data_home 
Example 20
Project: Python-GUI-Programming-with-Tkinter   Author: PacktPublishing   File: application.py    License: MIT License 6 votes vote down vote up
def load_settings(self):
        """Load settings into our self.settings dict."""

        vartypes = {
            'bool': tk.BooleanVar,
            'str': tk.StringVar,
            'int': tk.IntVar,
            'float': tk.DoubleVar
        }

        # create our dict of settings variables from the model's settings.
        self.settings = {}
        for key, data in self.settings_model.variables.items():
            vartype = vartypes.get(data['type'], tk.StringVar)
            self.settings[key] = vartype(value=data['value'])

        # put a trace on the variables so they get stored when changed.
        for var in self.settings.values():
            var.trace('w', self.save_settings) 
Example 21
Project: Python-GUI-Programming-with-Tkinter   Author: PacktPublishing   File: application.py    License: MIT License 6 votes vote down vote up
def load_settings(self):
        """Load settings into our self.settings dict."""

        vartypes = {
            'bool': tk.BooleanVar,
            'str': tk.StringVar,
            'int': tk.IntVar,
            'float': tk.DoubleVar
        }

        # create our dict of settings variables from the model's settings.
        self.settings = {}
        for key, data in self.settings_model.variables.items():
            vartype = vartypes.get(data['type'], tk.StringVar)
            self.settings[key] = vartype(value=data['value'])

        # put a trace on the variables so they get stored when changed.
        for var in self.settings.values():
            var.trace('w', self.save_settings) 
Example 22
Project: Python-GUI-Programming-with-Tkinter   Author: PacktPublishing   File: application.py    License: MIT License 6 votes vote down vote up
def database_login(self):
        """Try to login to the database and create self.data_model"""
        error = ''
        db_host = self.settings['db_host'].get()
        db_name = self.settings['db_name'].get()
        title = "Login to {} at {}".format(db_name, db_host)
        while True:
            login = v.LoginDialog(self, title, error)
            if not login.result:
                break
            else:
                username, password = login.result
                try:
                    self.data_model = m.SQLModel(
                        db_host, db_name, username, password)
                except m.pg.OperationalError:
                    error = "Login Failed"
                else:
                    break 
Example 23
Project: Python-GUI-Programming-with-Tkinter   Author: PacktPublishing   File: application.py    License: MIT License 6 votes vote down vote up
def get_tech_for_lab_check(self, *args):
        if not (
            hasattr(self, 'recordform')
            and self.settings['autofill sheet data'].get()
        ):
            return
        data = self.recordform.get()
        date = data['Date']
        time = data['Time']
        lab = data['Lab']

        if all([date, time, lab]):
            check = self.data_model.get_lab_check(date, time, lab)
            tech = check['lab_tech'] if check else ''
            self.recordform.inputs['Technician'].set(tech)
            self.recordform.focus_next_empty() 
Example 24
Project: Python-GUI-Programming-with-Tkinter   Author: PacktPublishing   File: application.py    License: MIT License 6 votes vote down vote up
def update_weather_data(self):

        try:
            weather_data = n.get_local_weather(
                self.settings['weather_station'].get()
            )
        except Exception as e:
            messagebox.showerror(
                title='Error',
                message='Problem retrieving weather data',
                detail=str(e)
            )
            self.status.set('Problem retrieving weather data')
        else:
            self.data_model.add_weather_data(weather_data)
            self.status.set(
                'Weather data recorded for {}'
                .format(weather_data['observation_time_rfc822'])
            ) 
Example 25
Project: cyberdisc-bot   Author: CyberDiscovery   File: constants.py    License: MIT License 5 votes vote down vote up
def getenv(name: str, fallback: str = "") -> str:
    """Return an (optionally base64-encoded) env var."""
    variable = environ.get(name)
    if DEPLOY and variable is not None:
        variable = base64.b64decode(variable).decode()
    return variable or fallback 
Example 26
Project: spleeter   Author: deezer   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_default_model_provider():
    """ Builds and returns a default model provider.

    :returns: A default model provider instance to use.
    """
    from .github import GithubModelProvider
    host = environ.get('GITHUB_HOST', 'https://github.com')
    repository = environ.get('GITHUB_REPOSITORY', 'deezer/spleeter')
    release = environ.get('GITHUB_RELEASE', GithubModelProvider.LATEST_RELEASE)
    return GithubModelProvider(host, repository, release) 
Example 27
Project: Authenticator   Author: bilelmoussaoui   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def can_use_qrscanner():
    desktop = environ.get("XDG_CURRENT_DESKTOP", "").lower()
    return desktop == "gnome" 
Example 28
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __repr__(self):
	dictionaryVariables = {N: 'N', V: 'V', ADJ: 'ADJ', ADV: 'ADV'}
	if dictionaryVariables.get(self):
	    return self.__module__ + "." + dictionaryVariables[self]
	return "<%s.%s instance for %s>" % (self.__module__, "Dictionary", self.pos) 
Example 29
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getWord(self, form, line=None):
	key = string.replace(string.lower(form), ' ', '_')
	pos = self.pos
	def loader(key=key, line=line, indexFile=self.indexFile):
	    line = line or indexFile.get(key)
	    return line and Word(line)
	word = _entityCache.get((pos, key), loader)
	if word:
	    return word
	else:
	    raise KeyError, "%s is not in the %s database" % (`form`, `pos`) 
Example 30
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getSynset(self, offset):
	pos = self.pos
	def loader(pos=pos, offset=offset, dataFile=self.dataFile):
	    return Synset(pos, offset, _lineAt(dataFile, offset))
	return _entityCache.get((pos, offset), loader)