Python environ.get方法代碼示例- 純淨天空

文章推薦指數: 80 %
投票人數:10人

需要導入模塊: 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:" "{}>".format(self.env.path) ) return self.line("Spawningshellwithin{}>".format(self.env.path)) #Settingthistoavoidspawningunnecessarynestedshells environ["POETRY_ACTIVE"]="1" shell=Shell.get() shell.activate(self.env) environ.pop("POETRY_ACTIVE")開發者ID:python-poetry,項目名稱:poetry,代碼行數:24,代碼來源:shell.py 示例17:finished ​點讚6 ​ #需要導入模塊:fromosimportenviron[as別名] #或者:fromos.environimportget[as別名] deffinished(): #ScrobbleifLast.fmissetup ifenviron.get('LAST_FM_ACTIVE'): song_info=queue.current_track() ifsong_infoisnotNoneand'title'insong_infoand'artist'insong_info: from..utilsimportlast_fm last_fm.scrobble( song_info['title'], song_info['artist'], environ['LAST_FM_SESSION_KEY'] ) queue.next() returnempty_response() ## #Intents #開發者ID:stevenleeg,項目名稱:geemusic,代碼行數:22,代碼來源:playback.py 示例18:get_data_home ​點讚6 ​ #需要導入模塊:fromosimportenviron[as別名] #或者:fromos.environimportget[as別名] defget_data_home(data_home=None): """Returnthepathofthestatsmodelsdatadir. Thisfolderisusedbysomelargedatasetloaderstoavoid downloadingthedataseveraltimes. Bydefaultthedatadirissettoafoldernamed'statsmodels_data' intheuserhomefolder. Alternatively,itcanbesetbythe'STATSMODELS_DATA'environment variableorprogramaticallybygivinganexplitfolderpath.The '~'symbolisexpandedtotheuserhomefolder. Ifthefolderdoesnotalreadyexist,itisautomaticallycreated. """ ifdata_homeisNone: data_home=environ.get('STATSMODELS_DATA', join('~','statsmodels_data')) data_home=expanduser(data_home) ifnotexists(data_home): makedirs(data_home) returndata_home開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:24,代碼來源:utils.py 示例19:load_settings ​點讚6 ​ #需要導入模塊:fromosimportenviron[as別名] #或者:fromos.environimportget[as別名] defload_settings(self): """Loadsettingsintoourself.settingsdict.""" vartypes={ 'bool':tk.BooleanVar, 'str':tk.StringVar, 'int':tk.IntVar, 'float':tk.DoubleVar } #createourdictofsettingsvariablesfromthemodel'ssettings. self.settings={} forkey,datainself.settings_model.variables.items(): vartype=vartypes.get(data['type'],tk.StringVar) self.settings[key]=vartype(value=data['value']) #putatraceonthevariablessotheygetstoredwhenchanged. forvarinself.settings.values(): var.trace('w',self.save_settings)開發者ID:PacktPublishing,項目名稱:Python-GUI-Programming-with-Tkinter,代碼行數:21,代碼來源:application.py 示例20:database_login ​點讚6 ​ #需要導入模塊:fromosimportenviron[as別名] #或者:fromos.environimportget[as別名] defdatabase_login(self): """Trytologintothedatabaseandcreateself.data_model""" error='' db_host=self.settings['db_host'].get() db_name=self.settings['db_name'].get() title="Loginto{}at{}".format(db_name,db_host) whileTrue: login=v.LoginDialog(self,title,error) ifnotlogin.result: break else: username,password=login.result try: self.data_model=m.SQLModel( db_host,db_name,username,password) exceptm.pg.OperationalError: error="LoginFailed" else: break開發者ID:PacktPublishing,項目名稱:Python-GUI-Programming-with-Tkinter,代碼行數:21,代碼來源:application.py 注:本文中的os.environ.get方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。



請為這篇文章評分?