Python os.environ.get() Examples

The following are 30 code examples of os.environ.get(). 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 also want to check out all available functions/classes of the module os.environ , or try the search function .
Example #1
Source File: base.py    From dephell with 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 #2
Source File: bootstrap_mycroft_db.py    From selene-backend with 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 #3
Source File: shell.py    From poetry with 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 #4
Source File: wordnet.py    From razzy-spinner with 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 #5
Source File: datasets_fetcher.py    From rankeval with 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 #6
Source File: playback.py    From geemusic with 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 #7
Source File: analyze.py    From brownie with 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 #8
Source File: config.py    From xenon with 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 #9
Source File: utils.py    From vnpy_crypto with 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 #10
Source File: install.py    From dephell with 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 #11
Source File: base.py    From pulse2percept with 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 #12
Source File: wordnet.py    From razzy-spinner with 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 #13
Source File: example-functions.py    From daudin with 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 #14
Source File: cassh_web.py    From cassh with 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 #15
Source File: base.py    From dephell with 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 #16
Source File: application.py    From Python-GUI-Programming-with-Tkinter with 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 #17
Source File: application.py    From Python-GUI-Programming-with-Tkinter with 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 #18
Source File: main.py    From linter-pylama with 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 #19
Source File: application.py    From Python-GUI-Programming-with-Tkinter with 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 #20
Source File: application.py    From Python-GUI-Programming-with-Tkinter with 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 #21
Source File: test_galario.py    From galario with 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 #22
Source File: base.py    From dephell with 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 #23
Source File: application.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def set_font(self, *args):
        font_size = self.settings['font size'].get()
        font_names = ('TkDefaultFont', 'TkMenuFont', 'TkTextFont')
        for font_name in font_names:
            tk_font = nametofont(font_name)
            tk_font.config(size=font_size) 
Example #24
Source File: application.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def set_font(self, *args):
        font_size = self.settings['font size'].get()
        font_names = ('TkDefaultFont', 'TkMenuFont', 'TkTextFont')
        for font_name in font_names:
            tk_font = nametofont(font_name)
            tk_font.config(size=font_size) 
Example #25
Source File: application.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def save_settings(self, *args):
        """Save the current settings to a preferences file"""

        for key, variable in self.settings.items():
            self.settings_model.set(key, variable.get())
        self.settings_model.save() 
Example #26
Source File: application.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def on_file_select(self):
        """Handle the file->select action from the menu"""

        filename = filedialog.asksaveasfilename(
            title='Select the target file for saving records',
            defaultextension='.csv',
            filetypes=[('CSV', '*.csv *.CSV')]
        )
        if filename:
            self.filename.set(filename)
            self.data_model = m.CSVModel(filename=self.filename.get())
            self.populate_recordlist()
            self.inserted_rows = []
            self.updated_rows = [] 
Example #27
Source File: aws_lambda.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_cloudwatch_logs_url(context, start_time):
    # type: (Any, datetime) -> str
    """
    Generates a CloudWatchLogs console URL based on the context object

    Arguments:
        context {Any} -- context from lambda handler

    Returns:
        str -- AWS Console URL to logs.
    """
    formatstring = "%Y-%m-%dT%H:%M:%S"

    url = (
        "https://console.aws.amazon.com/cloudwatch/home?region={region}"
        "#logEventViewer:group={log_group};stream={log_stream}"
        ";start={start_time};end={end_time}"
    ).format(
        region=environ.get("AWS_REGION"),
        log_group=context.log_group_name,
        log_stream=context.log_stream_name,
        start_time=(start_time - timedelta(seconds=1)).strftime(formatstring),
        end_time=(datetime.now() + timedelta(seconds=2)).strftime(formatstring),
    )

    return url 
Example #28
Source File: test_bin_rucio.py    From rucio with Apache License 2.0 5 votes vote down vote up
def test_list_account_usage(self):
        """ CLIENT (USER): list account usage. """
        if environ.get('SUITE', 'all') != 'client':
            from rucio.db.sqla import session, models
            from rucio.core.account_counter import increase
            db_session = session.get_session()
            db_session.query(models.AccountUsage).delete()
            db_session.query(models.AccountLimit).delete()
            db_session.query(models.AccountGlobalLimit).delete()
            db_session.query(models.UpdatedAccountCounter).delete()
            db_session.commit()
            rse = 'MOCK4'
            rse_id = self.rse_client.get_rse(rse)['id']
            rse_exp = 'MOCK|MOCK4'
            account = 'root'
            usage = 4
            local_limit = 10
            local_left = local_limit - usage
            global_limit = 20
            global_left = global_limit - usage
            self.account_client.set_local_account_limit(account, rse, local_limit)
            self.account_client.set_global_account_limit(account, rse_exp, global_limit)
            increase(rse_id, InternalAccount(account), 1, usage)
            abacus_account.run(once=True)
            cmd = 'rucio list-account-usage {0}'.format(account)
            exitcode, out, err = execute(cmd)
            nose.tools.assert_not_equal(re.search('.*{0}.*{1}.*{2}.*{3}'.format(rse, usage, local_limit, local_left), out), None)
            nose.tools.assert_not_equal(re.search('.*{0}.*{1}.*{2}.*{3}'.format(rse_exp, usage, global_limit, global_left), out), None)
            cmd = 'rucio list-account-usage --rse {0} {1}'.format(rse, account)
            exitcode, out, err = execute(cmd)
            nose.tools.assert_not_equal(re.search('.*{0}.*{1}.*{2}.*{3}'.format(rse, usage, local_limit, local_left), out), None)
            nose.tools.assert_not_equal(re.search('.*{0}.*{1}.*{2}.*{3}'.format(rse_exp, usage, global_limit, global_left), out), None)
            self.account_client.set_local_account_limit(account, rse, -1)
            self.account_client.set_global_account_limit(account, rse_exp, -1) 
Example #29
Source File: test_bin_rucio.py    From rucio with Apache License 2.0 5 votes vote down vote up
def test_add_delete_add_file(self):
        """CLIENT(USER): Add/Delete/Add"""
        tmp_file1 = file_generator()
        # add file
        cmd = 'rucio upload --rse {0} --scope {1} {2}'.format(self.def_rse, self.user, tmp_file1)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        # get the rule for the file
        cmd = "rucio list-rules {0}:{1} | grep {0}:{1} | cut -f1 -d\ ".format(self.user, tmp_file1[5:])  # NOQA: W605
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        rule = out
        # delete the file from the catalog
        cmd = "rucio delete-rule {0}".format(rule)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        # delete the fisical file
        cmd = "find /tmp/rucio_rse/ -name {0} |xargs rm".format(tmp_file1[5:])
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        # modify the file to avoid same checksum
        cmd = "echo 'delta' >> {0}".format(tmp_file1)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        # add the same file
        cmd = 'rucio upload --rse {0} --scope {1} {2}'.format(self.def_rse, self.user, tmp_file1)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        nose.tools.assert_equal(re.search("File {0}:{1} successfully uploaded on the storage".format(self.user, tmp_file1[5:]), out), None) 
Example #30
Source File: test_bin_rucio.py    From rucio with Apache License 2.0 5 votes vote down vote up
def test_upload_repeated_file(self):
        """CLIENT(USER): Rucio upload repeated files"""
        # One of the files to upload is already catalogued but was removed
        tmp_file1 = file_generator()
        tmp_file2 = file_generator()
        tmp_file3 = file_generator()
        tmp_file1_name = path.basename(tmp_file1)
        cmd = 'rucio -v upload --rse {0} --scope {1} {2}'.format(self.def_rse, self.user, tmp_file1)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out)
        print(err)
        # get the rule for the file
        cmd = "rucio list-rules {0}:{1} | grep {0}:{1} | cut -f1 -d\ ".format(self.user, tmp_file1_name)  # NOQA: W605
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        rule = out
        # delete the file from the catalog
        cmd = "rucio delete-rule {0}".format(rule)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        # delete the physical file
        cmd = "find /tmp/rucio_rse/ -name {0} |xargs rm".format(tmp_file1_name)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out, err)
        cmd = 'rucio -v upload --rse {0} --scope {1} {2} {3} {4}'.format(self.def_rse, self.user, tmp_file1, tmp_file2, tmp_file3)
        print(self.marker + cmd)
        exitcode, out, err = execute(cmd)
        print(out)
        print(err)
        remove(tmp_file1)
        remove(tmp_file2)
        remove(tmp_file3)
        upload_string_1 = (self.upload_success_str % tmp_file1_name)
        nose.tools.assert_true(upload_string_1 in out or upload_string_1 in err)