本文整理匯總了Python中os.environ.get方法的典型用法代碼示例。如果您正苦於以下問題:Python environ.get方法的具體用法?Python environ.get怎麽用?Python environ.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os.environ
的用法示例。
在下文中一共展示了environ.get方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例2: get
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例3: get_mythx_client
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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__}")]
)
示例4: get_data_dir
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例5: _myPrompt
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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)
示例6: requires_auth
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例7: __init__
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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)
示例8: test_FFT
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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)
示例9: _get_locked
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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)
示例10: _resolve
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例11: _get_loader_config_for_lockfile
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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']
示例12: bin_dir
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例13: __getattr__
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例14: __get_data_home__
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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
示例15: __init__
# 需要導入模塊: from os import environ [as 別名]
# 或者: from os.environ import get [as 別名]
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