Python environ.get方法代碼示例- 純淨天空
文章推薦指數: 80 %
需要導入模塊: from os import environ [as 別名] # 或者: from os.environ import get [as 別名] def get(self, model_directory): """ Ensures required model is ...
當前位置:首頁>>代碼示例>>Python>>正文
本文整理匯總了Python中os.environ.get方法的典型用法代碼示例。
如果您正苦於以下問題:Pythonenviron.get方法的具體用法?Pythonenviron.get怎麽用?Pythonenviron.get使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。
您也可以進一步了解該方法所在類os.environ的用法示例。
在下文中一共展示了environ.get方法的20個代碼示例,這些例子默認根據受歡迎程度排序。
您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1:get
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defget(self,model_directory):
"""Ensuresrequiredmodelisavailableatgivenlocation.
:parammodel_directory:Expectedmodel_directorytobeavailable.
:raiseIOError:Ifmodelcannotberetrieved.
"""
#Expendmodeldirectoryifneeded.
ifnotisabs(model_directory):
model_directory=join(self.DEFAULT_MODEL_PATH,model_directory)
#Downloaditifnotexists.
model_probe=join(model_directory,self.MODEL_PROBE_PATH)
ifnotexists(model_probe):
ifnotexists(model_directory):
makedirs(model_directory)
self.download(
model_directory.split(sep)[-1],
model_directory)
self.writeProbe(model_directory)
returnmodel_directory開發者ID:deezer,項目名稱:spleeter,代碼行數:21,代碼來源:__init__.py
示例2:get
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defget(this,key,loadfn=None):
value=None
ifthis.values:
pair=this.values.get(key)
ifpair:
(value,timestamp)=pair
delthis.history[timestamp]
ifvalue==None:
value=loadfnandloadfn()
ifthis.values!=None:
timestamp=this.nextTimestamp
this.nextTimestamp=this.nextTimestamp+1
this.values[key]=(value,timestamp)
this.history[timestamp]=key
iflen(this.values)>this.capacity:
this.removeOldestEntry()
returnvalue開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:19,代碼來源:wordnet.py
示例3:get_mythx_client
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defget_mythx_client()->Client:
"""GenerateaMythXclientinstance.
ThismethodwilllookforanAPIkeypassedasaparameter,andifnone
isfound,lookforakeyintheenvironmentvariable:code:`MYTHX_API_KEY`.
Ifakeyisdetected,aPythXclientinstanceisreturned,otherwisea
:code:`ValidationError`israised.
:raises:ValidationErrorifnovalidAPIkeyisprovided
:return:APythXclientinstance
"""
ifCONFIG.argv["api-key"]:
auth_args={"api_key":CONFIG.argv["api-key"]}
elifenviron.get("MYTHX_API_KEY"):
auth_args={"api_key":environ.get("MYTHX_API_KEY")}
else:
raiseValidationError(
"YoumustprovideaMythXAPIkeyviaenvironmentvariableorthecommandline"
)
returnClient(
**auth_args,middlewares=[ClientToolNameMiddleware(name=f"brownie-{__version__}")]
)開發者ID:eth-brownie,項目名稱:brownie,代碼行數:26,代碼來源:analyze.py
示例4:get_data_dir
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defget_data_dir(data_dir=None):
"""Returnthepathofthepulse2perceptdatadirectory
Thisdirectoryisusedtostorethedatasetsretrievedbythedatafetch
utilityfunctionstoavoiddownloadingthedataseveraltimes.
Bydefault,thisissettoadirectorycalled'pulse2percept_data'inthe
userhomedirectory.
Alternatively,itcanbesetbya``PULSE2PERCEPT_DATA``environment
variableorsetprogrammaticallybyspecifyingapath.
Ifthedirectorydoesnotalreadyexist,itisautomaticallycreated.
Parameters
----------
data_dir:str|None
Thepathtothepulse2perceptdatadirectory.
"""
ifdata_dirisNone:
data_dir=environ.get('PULSE2PERCEPT_DATA',
join('~','pulse2percept_data'))
data_dir=expanduser(data_dir)
ifnotexists(data_dir):
makedirs(data_dir)
returndata_dir開發者ID:pulse2percept,項目名稱:pulse2percept,代碼行數:27,代碼來源:base.py
示例5:_myPrompt
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def_myPrompt():
BLUE='\033[94m'
GREEN='\033[92m'
NORM='\033[0m'
cwd=getcwd()
cwdStr='%s%s%s'%(
GREEN,
'~'ifcwd==environ.get('HOME')elsebasename(cwd),
NORM)
#Notethatifgitfailstofindarepo,itprintstostderrandexits
#non-zero(bothofwhichweignore).
status=run('gitsymbolic-refHEAD--short',shell=True,
universal_newlines=True,capture_output=True).stdout.strip()
gitStr='%s(%s)%s'%(BLUE,status,NORM)ifstatuselse''
return'%s%s>>>'%(cwdStr,gitStr)開發者ID:terrycojones,項目名稱:daudin,代碼行數:20,代碼來源:example-functions.py
示例6:requires_auth
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defrequires_auth(func):
"""Wrapperwhichforceauthentication"""
@wraps(func)
defdecorated(*args,**kwargs):
"""Authenticationwrapper"""
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'
ifcurrent_user['name']=='Unknown'andcurrent_user['password']=='Unknown':
current_user['is_authenticated']=False
returnfunc(current_user=current_user,*args,**kwargs)
returndecorated開發者ID:nbeguier,項目名稱:cassh,代碼行數:18,代碼來源:cassh_web.py
示例7:__init__
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[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)
ifop.exists(HOME_RCFILE):
rcfile=HOME_RCFILE
ifselect:
enable=select|set(enable.split(",")ifenableelse[])
ifignore:
disable=ignore|set(disable.split(",")ifdisableelse[])
params.update(dict(
rcfile=rcfile,enable=enable,disable=disable))
self.params=dict(
(name.replace('_','-'),self.prepare_value(value))
forname,valueinparams.items()ifvalueisnotNone)開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:24,代碼來源:main.py
示例8:test_FFT
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
deftest_FFT(size,real_type,rtol,atol,acc_lib):
"""
TesttheRealtoComplexFFTW/cuFFTagainstnumpyComplextoComplex.
"""
reference_image=create_reference_image(size=size,dtype=real_type)
ft=np.fft.fft2(reference_image)
acc_res=acc_lib._fft2d(reference_image)
#outputsofdifferentshapebecausenpdoesn'tusetheredundancyy[i]==y[n-i]fori>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)
#somerealpartscanbeveryclosetozero,soweneedatol>0!
#onlygetthe0-thandthefirsthalfofcolumnstocomparetocompactFFTWoutput
assert_allclose(unique_part(ft).real,acc_res.real,rtol,atol)
assert_allclose(unique_part(ft).imag,acc_res.imag,rtol,atol)開發者ID:mtazzari,項目名稱:galario,代碼行數:21,代碼來源:test_galario.py
示例9:_get_locked
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def_get_locked(self,default_envs:Set[str]=None):
if'from'notinself.config:
python=get_python_env(config=self.config)
self.logger.debug('choosenpython',extra=dict(path=str(python.path)))
resolver=InstalledConverter().load_resolver(paths=python.lib_paths)
returnself._resolve(resolver=resolver,default_envs=default_envs)
loader_config=self._get_loader_config_for_lockfile()
ifnotPath(loader_config['path']).exists():
self.logger.error('cannotfinddependencyfile',extra=dict(path=loader_config['path']))
returnNone
self.logger.info('getdependencies',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)
returnself._resolve(resolver=resolver,default_envs=default_envs)開發者ID:dephell,項目名稱:dephell,代碼行數:23,代碼來源:base.py
示例10:_resolve
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def_resolve(self,resolver,default_envs:Set[str]=None):
#resolve
iflen(resolver.graph._layers)<=1:#ifitisn'tresolvedyet
self.logger.info('builddependenciesgraph...')
resolved=resolver.resolve(silent=self.config['silent'])
ifnotresolved:
conflict=analyze_conflict(resolver=resolver)
self.logger.warning('conflictwasfound')
print(conflict)
returnNone
#applyenvsifneeded
ifself.config.get('envs'):
resolver.apply_envs(set(self.config['envs']))
elifdefault_envs:
resolver.apply_envs(default_envs)
returnresolver開發者ID:dephell,項目名稱:dephell,代碼行數:20,代碼來源:base.py
示例11:_get_loader_config_for_lockfile
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def_get_loader_config_for_lockfile(self)->Dict[str,str]:
#ifpathspecifiedinCLI,useit
ifset(self.args.__dict__)&{'from','from_format','from_path'}:
returnself.config['from']
dumper_config=self.config.get('to')
ifnotdumper_configordumper_config=='stdout':
returnself.config['from']
ifnotPath(dumper_config['path']).exists():
returnself.config['from']
dumper=CONVERTERS[dumper_config['format']]
ifdumper.lock:
returndumper_config
returnself.config['from']開發者ID:dephell,項目名稱:dephell,代碼行數:19,代碼來源:base.py
示例12:bin_dir
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defbin_dir(self)->Path:
"""GlobaldirectoryfromPATHtosimlinkdephell'sbinary
"""
path=Path.home()/'.local'/'bin'
ifpath.exists():
returnpath
paths=[Path(path)forpathinenviron.get('PATH','').split(pathsep)]
forpathinpaths:
ifpath.exists()and'.local'inpath.parts:
returnpath
forpathinpaths:
ifpath.exists():
returnpath
raiseLookupError('cannotfindplacetoinstallbinary',paths)
#actions開發者ID:dephell,項目名稱:dephell,代碼行數:18,代碼來源:install.py
示例13:__getattr__
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def__getattr__(name):
default=getattr(Config,name,None)
value=env.get(name.upper())
ifvalueisnotNone:
ifisinstance(default,int):
returnint(value)
ifisinstance(default,float):
returnfloat(value)
ifisinstance(default,bool):
valid=["y","yes","true"]
returnvalue.lower()invalid
ifisinstance(default,list):
returnvalue.split(",")
returnvalue
returndefault開發者ID:Xenon-Bot,項目名稱:xenon,代碼行數:23,代碼來源:config.py
示例14:__get_data_home__
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
def__get_data_home__(data_home=None):
"""
Returnthepathoftherankevaldatadir.
Thisfolderisusedbysomelargedatasetloaderstoavoid
downloadingthedataseveraltimes.
Bydefaultthedatadirissettoafoldernamed'rankeval_data'
intheuserhomefolder.
Alternatively,itcanbesetbythe'RANKEVAL_DATA'environment
variableorprogrammaticallybygivinganexplicitfolderpath.The
'~'symbolisexpandedtotheuserhomefolder.
Ifthefolderdoesnotalreadyexist,itisautomaticallycreated.
"""
ifdata_homeisNone:
data_home=environ.get('RANKEVAL_DATA',join('~','rankeval_data'))
data_home=expanduser(data_home)
ifnotexists(data_home):
makedirs(data_home)
returndata_home開發者ID:hpclab,項目名稱:rankeval,代碼行數:20,代碼來源:datasets_fetcher.py
示例15:__init__
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[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')
ifdb_namein('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']
ifuserisnotNone:
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開發者ID:MycroftAI,項目名稱:selene-backend,代碼行數:25,代碼來源:bootstrap_mycroft_db.py
示例16:handle
點讚6
#需要導入模塊:fromosimportenviron[as別名]
#或者:fromos.environimportget[as別名]
defhandle(self):
frompoetry.utils.shellimportShell
#Checkifit'salreadyactivatedordoesn'texistandwon'tbecreated
venv_activated=strtobool(environ.get("POETRY_ACTIVE","0"))orgetattr(
sys,"real_prefix",sys.prefix
)==str(self.env.path)
ifvenv_activated:
self.line(
"Virtualenvironmentalreadyactivated:"
"
延伸文章資訊
- 1How do I access environment variables in Python? - Stack ...
Environment variables are accessed through os.environ import os print(os.environ['HOME']). Or you...
- 2os --- 多种操作系统接口— Python 3.10.4 說明文件
在Python 中,使用字符串类型表示文件名、命令行参数和环境变量。 ... 直接调用 putenv() 并不会影响 os.environ ,所以推荐直接修改 os.environ 。
- 3os.environ模块环境变量详解 - CSDN博客
1、os.environ() 详解. 在python 中通过os.environ 可以获取有关系统的各种信息. 1.1 简介. 通过os.environ 获取环境变量,什么是环境变量呢?
- 4Python os.environ方法代碼示例- 純淨天空
Python os.environ使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類 os 的 ...
- 5【PYTHON】os.environ沒有設定環境變數 - 程式人生
【PYTHON】os.environ沒有設定環境變數. 2020-11-03 PYTHON. 這個問題已經有了答案: How do I make environment variable cha...