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

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

Python os.environ使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。

您也可以進一步了解該方法所在類 os 的 ... 當前位置:首頁>>代碼示例>>Python>>正文 本文整理匯總了Python中os.environ方法的典型用法代碼示例。

如果您正苦於以下問題:Pythonos.environ方法的具體用法?Pythonos.environ怎麽用?Pythonos.environ使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。

您也可以進一步了解該方法所在類os的用法示例。

在下文中一共展示了os.environ方法的20個代碼示例,這些例子默認根據受歡迎程度排序。

您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。

示例1:get_settings ​點讚7 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_settings(self): """ReturntheDynamoDBaws-auto-remediate-settingstableinaPythondictformat Returns: dict--aws-auto-remediate-settingstable """ settings={} try: forrecordinboto3.client("dynamodb").scan( TableName=os.environ["SETTINGSTABLE"] )["Items"]: record_json=dynamodb_json.loads(record,True) settings[record_json["key"]]=record_json["value"] except: self.logging.error( f"CouldnotreadDynamoDBtable'{os.environ['SETTINGSTABLE']}'." ) self.logging.error(sys.exc_info()[1]) returnsettings開發者ID:servian,項目名稱:aws-auto-remediate,代碼行數:22,代碼來源:lambda_handler.py 示例2:find_executable ​點讚7 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] deffind_executable(name)->str: is_windows=os.name=='nt' windows_exts=os.environ['PATHEXT'].split(ENV_PATH_SEP)ifis_windowselseNone path_dirs=os.environ['PATH'].split(ENV_PATH_SEP) search_dirs=path_dirs+[os.getcwd()]#cwdislastinthelist fordirinsearch_dirs: path=os.path.join(dir,name) ifis_windows: forextensioninwindows_exts: path_with_ext=path+extension ifos.path.isfile(path_with_ext)andos.access(path_with_ext,os.X_OK): returnpath_with_ext else: ifos.path.isfile(path)andos.access(path,os.X_OK): returnpath return''開發者ID:godotengine,項目名稱:godot-mono-builds,代碼行數:23,代碼來源:os_utils.py 示例3:__init__ ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] def__init__(self,methodName,prop_file="models/grid_for_test.props"): super().__init__(methodName=methodName) self.pa=props.read_props(MODEL_NM,prop_file) #Nowwecreateaforestenvironmentforouragentstoactwithin: ifself.pa["user_type"]==props.WEB: self.pa["base_dir"]=os.environ["base_dir"] #Nowwecreateaminimalenvironmentforouragentstoactwithin: self.env=ge.GridEnv("Testgridenv", self.pa["grid_width"], self.pa["grid_height"], torus=False, model_nm=MODEL_NM, preact=True, postact=True, props=self.pa) foriinrange(self.pa["num_agents"]): self.env.add_agent(gm.TestGridAgent(name="agent"+str(i), goal="takingupagridspace!")) self.env.add_agent(gm.TestGridAgent(name="agentfortracking", goal="takingupagridspace!"))開發者ID:gcallah,項目名稱:indras_net,代碼行數:27,代碼來源:test_grid.py 示例4:run_migrations_online ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defrun_migrations_online(): """Runmigrationsin'online'mode. InthisscenarioweneedtocreateanEngine andassociateaconnectionwiththecontext. """ db_url=os.environ['DRYDOCK_DB_URL'] connectable=engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool, url=db_url) withconnectable.connect()asconnection: context.configure( connection=connection,target_metadata=target_metadata) withcontext.begin_transaction(): context.run_migrations()開發者ID:airshipit,項目名稱:drydock,代碼行數:23,代碼來源:env.py 示例5:put ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defput(args): ifargs.generate_ssh_key: ssh_key=new_ssh_key() buf=StringIO() ssh_key.write_private_key(buf) secret_value=buf.getvalue() elifargs.secret_nameinos.environ: secret_value=os.environ[args.secret_name] else: secret_value=sys.stdin.read() try: res=clients.secretsmanager.create_secret(Name=args.secret_name,SecretString=secret_value) exceptclients.secretsmanager.exceptions.ResourceExistsException: res=clients.secretsmanager.put_secret_value(SecretId=args.secret_name,SecretString=secret_value) ifparse_principal(args): ensure_policy(parse_principal(args),res["ARN"]) ifargs.generate_ssh_key: returndict(ssh_public_key=hostkey_line(hostnames=[],key=ssh_key).strip(), ssh_key_fingerprint=key_fingerprint(ssh_key))開發者ID:kislyuk,項目名稱:aegea,代碼行數:21,代碼來源:secrets.py 示例6:get_VT_name ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_VT_name(hashes): try: vt=PrivateApi(api_key=os.environ["VIRUSTOTAL_API_KEY"]) generator=ComputeVtUniqueName() names=[generator.build_unique_name(vt.get_file_report(hash_)or"")forhash_inhashes] iflen(names)>=2andall(names[0]==namefornameinnames[1:]): name=names[0] ifname["pup"]: log.error("PUAsignaturesarenotimplementedyet.Excpectednamewas:%s",str(name)) pass else: return"{}.{}.{}".format(name["platform"],name["category"],name["unique_name"]) exceptKeyError: log.warn("NoVIRUSTOTAL_API_KEYspecified.Fallingbacktogenericname.") exceptException: log.exception("WhitetryingtocomputeVTname.Fallingbacktogenericname.") returnGENERIC_CLAMAV_MALWARE_NAME開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:19,代碼來源:core.py 示例7:run_ida ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defrun_ida(db,is_64_bit,timeout,script,*args): ifos.path.exists(os.path.join(IDA_DIR,"idat")): #ThisisIDA>=7.0 IDA_EXECUTABLE=os.path.join(IDA_DIR,"idat") else: IDA_EXECUTABLE=os.path.join(IDA_DIR,"idal") ifis_64_bit: ida="{}64".format(IDA_EXECUTABLE) else: ida=IDA_EXECUTABLE cmd=(ida,"-S{}{}".format(script,"".join("\"{}\"".format(x)forxinargs)),"-B",db) env=os.environ.copy() env["TVHEADLESS"]="true" env["IDALOG"]=os.path.join(LOGS_DIR,datetime.datetime.strftime(datetime.datetime.now(),"ida_%Y-%m-%d_%H-%M-%S.%f.log")) logger.info("Executingcommand%s,logoutputisin'%s'","".join("'%s'"%xforxincmd),env["IDALOG"]) try: check_call(cmd,timeout=timeout,env=env) exceptOSErroraserr: iferr.errno==-9: raiseTimeoutError(err.errno,"Programexecutiontimedout") else: raiseerr開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:26,代碼來源:ida_service.py 示例8:index ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defindex(request): ctx=get_context(request) cname=os.environ["PORTAL_CNAME"] template_dir=get_app_template_dirs("templates/notebooks")[0] htmls=os.path.join(template_dir,cname,"*.html") ctx["notebooks"]=[ p.split("/"+cname+"/")[-1].replace(".html","")forpinglob(htmls) ] ctx["PORTAL_CNAME"]=cname ctx["landing_pages"]=[] mask=["project","title","authors","is_public","description","urls"] client=Client(headers=get_consumer(request))#sets/returnsglobalvariable entries=client.projects.get_entries(_fields=mask).result()["data"] forentryinentries: authors=entry["authors"].strip().split(",",1) iflen(authors)>1: authors[1]=authors[1].strip() entry["authors"]=authors entry["description"]=entry["description"].split(".",1)[0]+"." ctx["landing_pages"].append( entry )#visibilitygovernedbyis_publicflagandX-Consumer-Groupsheader returnrender(request,"home.html",ctx.flatten())開發者ID:materialsproject,項目名稱:MPContribs,代碼行數:25,代碼來源:views.py 示例9:from_environment ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] deffrom_environment(cls,context): """ Createanewdevicefromtheprocessenvironment(asin :data:`os.environ`). Thisonlyworksreliable,ifthecurrentprocessiscalledfroman udevrule,andisusuallyusedfortoolsexecutedfrom``IMPORT=`` rules.UsethismethodtocreatedeviceobjectsinPythonscripts calledfromudevrules. ``context``isthelibrary:class:`Context`. Returna:class:`Device`objectconstructedfromtheenvironment. Raise:exc:`DeviceNotFoundInEnvironmentError`,ifnodevicecouldbe createdfromtheenvironment. ..udevversion::152 ..versionadded::0.18 """ device=context._libudev.udev_device_new_from_environment(context) ifnotdevice: raiseDeviceNotFoundInEnvironmentError() returnDevice(context,device)開發者ID:mbusb,項目名稱:multibootusb,代碼行數:26,代碼來源:_device.py 示例10:send_to_missing_remediation_topic ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defsend_to_missing_remediation_topic(self,config_rule_name,config_payload): """PublishesamessageontothemissingremediationSNSTopic.Thetopicshouldbesubscribedto byadministratorstobeawarewhentheirsecurityremediationsarenotfullycovered. Arguments: config_rule_name{string}--AWSConfigRulename config_payload{dictionary}--AWSConfigRulepayload """ client=boto3.client("sns") topic_arn=os.environ["MISSINGREMEDIATIONTOPIC"] try: client.publish( TopicArn=topic_arn, Message=json.dumps(config_payload), Subject=f"NoremediationavailableforConfigRule'{config_rule_name}'", ) except: self.logging.error(f"CouldnotpublishtoSNSTopic'topic_arn'.")開發者ID:servian,項目名稱:aws-auto-remediate,代碼行數:21,代碼來源:lambda_handler.py 示例11:get_settings ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_settings(self): """ReturntheDynamoDBaws-auto-remediate-settingstableinaPythondictformat Returns: dict--aws-auto-remediate-settingstable """ settings={} try: forrecordinself.client_dynamodb.scan( TableName=os.environ["SETTINGSTABLE"] )["Items"]: record_json=dynamodb_json.loads(record,True) if"key"inrecord_jsonand"value"inrecord_json: settings[record_json.get("key")]=record_json.get("value") except: self.logging.error( f"CouldnotreadDynamoDBtable'{os.environ['SETTINGSTABLE']}'." ) self.logging.error(sys.exc_info()[1]) returnsettings開發者ID:servian,項目名稱:aws-auto-remediate,代碼行數:24,代碼來源:lambda_handler.py 示例12:test_invalid_table_schema ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] deftest_invalid_table_schema(self,setup): """TestsretrievalofsettingsfromDynamoDBwiththewrongschema Arguments: setup{class}--InstanceofSetupclass """ os.environ["SETTINGSTABLE"]="settings-table" setup.client_dynamodb.create_table( TableName="settings-table", KeySchema=[{"AttributeName":"id","KeyType":"HASH"}], AttributeDefinitions=[{"AttributeName":"id","AttributeType":"S"}], ProvisionedThroughput={"ReadCapacityUnits":1,"WriteCapacityUnits":1}, ) setup.client_dynamodb.put_item( TableName="settings-table",Item={"id":{"S":"123"}} ) #testget_settingsfunction assertsetup.get_settings()=={}開發者ID:servian,項目名稱:aws-auto-remediate,代碼行數:23,代碼來源:test_setup.py 示例13:_get_full_path ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] def_get_full_path(value): """ convertstringtoabsolutenormpath. @paramvalue:somestringtobeconverted @typevalue:basestring @return:absolutenormpath @rtype:basestring """ assertisinstance(value,basestring) parent_directory,filename=os.path.split(value) ifnotparent_directoryandnotos.path.isfile(value): forpathinos.environ["PATH"].split(os.pathsep): path=path.strip('"') exe_file=os.path.join(path,filename) ifos.path.isfile(exe_file): value=exe_file break value=os.path.expanduser(value) value=os.path.normpath(value) value=os.path.abspath(value) returnvalue開發者ID:CAMI-challenge,項目名稱:CAMISIM,代碼行數:25,代碼來源:configparserwrapper.py 示例14:update_complete ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defupdate_complete(self,client): logger.debug("Selfupdatesuccessful!Editmessage") heroku_key=os.environ.get("heroku_api_token") herokufail=("DYNO"inos.environ)and(heroku_keyisNone) ifherokufail: logger.warning("herokutokennotset") msg=self.strings["heroku_warning"] else: logger.debug("Selfupdatesuccessful!Editmessage") msg=self.strings["success"]ifrandom.randint(0,10)!=0elseself.strings["success_meme"] ifself.config["AUDIO"]: awaitclient.send_file(self._db.get(__name__,"selfupdatechat"),STARTUP,caption=msg,voice_note=True) awaitclient.delete_messages(self._db.get(__name__,"selfupdatechat"), [self._db.get(__name__,"selfupdatemsg")]) else: awaitclient.edit_message(self._db.get(__name__,"selfupdatechat"), self._db.get(__name__,"selfupdatemsg"),msg)開發者ID:friendly-telegram,項目名稱:friendly-telegram,代碼行數:19,代碼來源:updater.py 示例15:get_phones ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_phones(arguments): """Getphonesfromthe--token,--phone,andenvironment""" phones=set(arguments.phoneifarguments.phoneelse[]) phones.update(map(lambdaf:f[18:-8], filter(lambdaf:f.startswith("friendly-telegram-")andf.endswith(".session"), os.listdir(os.path.dirname(utils.get_base_dir()))))) authtoken=os.environ.get("authorization_strings",False)#forheroku ifauthtokenandnotarguments.setup: try: authtoken=json.loads(authtoken) exceptjson.decoder.JSONDecodeError: logging.warning("authtokeninvalid") authtoken=False ifarguments.setupor(arguments.tokensandnotauthtoken): authtoken={} ifarguments.tokens: fortokeninarguments.tokens: phone=sorted(phones).pop(0) phones.remove(phone)#Handledseperatelybyauthtokenlogic authtoken.update(**{phone:token}) returnphones,authtoken開發者ID:friendly-telegram,項目名稱:friendly-telegram,代碼行數:25,代碼來源:main.py 示例16:main ​點讚6 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defmain(): """ Mainapplicationloop. """ env=os.environ try: host=env['SYSLOG_SERVER'] port=int(env['SYSLOG_PORT']) socktype=socket.SOCK_DGRAMifenv['SYSLOG_PROTO']=='udp'\ elsesocket.SOCK_STREAM exceptKeyError: sys.exit("SYSLOG_SERVER,SYSLOG_PORTandSYSLOG_PROTOarerequired.") handler=SysLogHandler( address=(host,port), socktype=socktype, ) handler.setFormatter(PalletFormatter()) forevent_headers,event_datainsupervisor_events(sys.stdin,sys.stdout): event=logging.LogRecord( name=event_headers['processname'], level=logging.INFO, pathname=None, lineno=0, msg=event_data, args=(), exc_info=None, ) event.process=int(event_headers['pid']) handler.handle(event)開發者ID:infoxchange,項目名稱:supervisor-logging,代碼行數:35,代碼來源:__init__.py 示例17:get_prop_from_env ​點讚5 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_prop_from_env(): globaluser_type try: user_type=os.environ[UTYPE] exceptKeyError: #thiscan'tbedonebeforeloggingissetup! #logging.info("Environmentvariableusertypenotfound") user_type=TERMINAL returnuser_type開發者ID:gcallah,項目名稱:indras_net,代碼行數:11,代碼來源:prop_args2.py 示例18:__init__ ​點讚5 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] def__init__(self,model_nm,logfile=None,prop_dict=None, loglevel=logging.INFO): """ Loadsandsetspropertiesinthefollowingorder: 1.TheDatabase 2.TheUser'sEnvironment(operatingsystem,dev/prodsettings,etc.) 3.PropertyFile 4.CommandLine 5.QuestionsPromptsDuringRun-Time """ self.logfile=logfile self.model_nm=model_nm self.graph=nx.Graph() self.props={} #1.TheDatabase self.set_props_from_db() #2.TheEnvironment self.overwrite_props_from_env() #3.PropertyFile self.overwrite_props_from_dict(prop_dict) ifself.props[UTYPE].valin(TERMINAL,IPYTHON,IPYTHON_NB): #4.processcommandlineargsandsetthemasproperties: self.overwrite_props_from_cl() #5.Asktheuserquestions. self.overwrite_props_from_user() elifself.props[UTYPE].val==WEB: self.props[PERIODS]=Prop(val=1) self.props[BASE_DIR]=Prop(val=os.environ[BASE_DIR]) self.logger=Logger(self,model_name=model_nm,logfile=logfile) self.graph.add_edge(self,self.logger)開發者ID:gcallah,項目名稱:indras_net,代碼行數:39,代碼來源:prop_args2.py 示例19:get_prop_from_env ​點讚5 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defget_prop_from_env(prop_nm): globaluser_type try: user_type=os.environ['user_type'] exceptKeyError: #thiscan'tbedonebeforeloggingissetup! #logging.info("Environmentvariableusertypenotfound") user_type=TERMINAL returnuser_type開發者ID:gcallah,項目名稱:indras_net,代碼行數:11,代碼來源:prop_args.py 示例20:run ​點讚5 ​ #需要導入模塊:importos[as別名] #或者:fromosimportenviron[as別名] defrun(prop_dict=None): pa=props.PropArgs.create_props(MODEL_NM,prop_dict) importindra.utilsasutils importschelling.segregationassm #setupsomefilenames: (prog_file,log_file,prop_file,results_file)=utils.gen_file_names(MODEL_NM) #Westorebasicparametersina"property"file;thisallowsustosave #multipleparametersets,whichisimportantinsimulationwork. #Wecanreadtheseinfromfileorsetthemhere. ifpa["user_type"]==props.WEB: pa["base_dir"]=os.environ['base_dir'] #Nowwecreateanenvironmentforouragentstoactwithin: env=sm.SegregationEnv("Acity", pa["grid_width"], pa["grid_height"], model_nm=pa.model_nm, props=pa) #Nowweloopcreatingmultipleagentswithnumberednames #basedontheloopvariable: foriinrange(pa["num_B_agents"]): env.add_agent(sm.BlueAgent(name="Blueagent"+str(i), goal="Agoodneighborhood.", min_tol=pa['min_tolerance'], max_tol=pa['max_tolerance'], max_detect=pa['max_detect'])) foriinrange(pa["num_R_agents"]): env.add_agent(sm.RedAgent(name="Redagent"+str(i), goal="Agoodneighborhood.", min_tol=pa['min_tolerance'], max_tol=pa['max_tolerance'], max_detect=pa['max_detect'])) returnutils.run_model(env,prog_file,results_file)開發者ID:gcallah,項目名稱:indras_net,代碼行數:41,代碼來源:segregation_run.py 注:本文中的os.environ方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。



請為這篇文章評分?