• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python environ.has_key函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中os.environ.has_key函数的典型用法代码示例。如果您正苦于以下问题:Python has_key函数的具体用法?Python has_key怎么用?Python has_key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了has_key函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: create_ec2_connection

def create_ec2_connection(hostname=None, path=None, port=None):
    if hostname == None:
        # We're using EC2.
        # Check for AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY,
        # and use EC2Connection. boto will fill in all the values
        if not (environ.has_key("AWS_ACCESS_KEY_ID") and environ.has_key("AWS_SECRET_ACCESS_KEY")):
            return None
        else:
            return EC2Connection()
    else:
        # We're using an EC2-ish cloud.
        # Check for EC2_ACCESS_KEY and EC2_SECRET_KEY (these are used by Eucalyptus;
        # we will probably have to tweak this further to support other systems)
        if not (environ.has_key("EC2_ACCESS_KEY") and environ.has_key("EC2_SECRET_KEY")):
            return None
        else:
            print "Setting region"
            region = RegionInfo(name="eucalyptus", endpoint=hostname)
            return connect_ec2(
                aws_access_key_id=environ["EC2_ACCESS_KEY"],
                aws_secret_access_key=environ["EC2_SECRET_KEY"],
                is_secure=False,
                region=region,
                port=port,
                path=path,
            )
开发者ID:pombredanne,项目名称:provision,代码行数:26,代码来源:utils.py


示例2: get_plugin_dirs

def get_plugin_dirs():
  PLUGINS = []
  PLUGINS_DIRS = []
  PLUGINS_DIRS += [os.path.join(d, "gwibber", "plugins") for d in DATA_BASE_DIRS]

  if exists(os.path.join("gwibber", "microblog", "plugins")):
    PLUGINS_DIRS.insert(0, os.path.realpath(os.path.join("gwibber", "microblog", "plugins")))

  if exists(os.path.join("gwibber", "plugins")):
    PLUGINS_DIRS.insert(0, os.path.realpath(os.path.join("gwibber", "plugins")))

  if environ.has_key("GWIBBER_PLUGIN_DIR"):
    GWIBBER_PLUGIN_DIR = environ["GWIBBER_PLUGIN_DIR"]
    if exists(os.path.realpath(GWIBBER_PLUGIN_DIR)):
      PLUGINS_DIRS.insert(0, os.path.realpath(GWIBBER_PLUGIN_DIR))

  PLUGINS_DIRS.reverse()

  if environ.has_key("GWIBBER_PLUGIN_TEST_DIR"):
    PLUGINS_DIRS = []
    PLUGINS_DIRS.insert (0, os.path.realpath(environ["GWIBBER_PLUGIN_TEST_DIR"]))

  for p in PLUGINS_DIRS:
    if exists(p):
      sys.path.insert(0, p)
      for d in os.listdir(p):
        if os.path.isdir(os.path.join(p, d)):
          if d not in PLUGINS:
            PLUGINS.append(d)
  return [PLUGINS,PLUGINS_DIRS] 
开发者ID:thnguyn2,项目名称:ECE_527_MP,代码行数:30,代码来源:resources.py


示例3: end

def end(summary,perfdata,longserviceoutput,nagios_state):
	global show_longserviceoutput
	global show_perfdata
	global nagios_server
	global do_phone_home
	global nagios_port
	global nagios_myhostname
	global hostname
	global mode
	global escape_newlines
	global check_system

	message = "%s - %s" % ( state[nagios_state], summary)
	if show_perfdata:
		message = "%s | %s" % ( message, perfdata)
	if show_longserviceoutput:
		message = "%s\n%s" % ( message, longserviceoutput.strip())
	if escape_newlines == True:
		lines = message.split('\n')
		message = '\\n'.join(lines)
	debug( "do_phone_home = %s" %(do_phone_home) )
	if do_phone_home == True:
		try:
			if nagios_myhostname is None:
				if environ.has_key( 'HOSTNAME' ):
					nagios_myhostname = environ['HOSTNAME']
				elif environ.has_key( 'COMPUTERNAME' ):
					nagios_myhostname = environ['COMPUTERNAME']
				else:
					nagios_myhostname = hostname
			phone_home(nagios_server,nagios_port, status=nagios_state, message=message, hostname=nagios_myhostname, servicename=mode,system=check_system)
		except:
			raise
	print message
	exit(nagios_state)
开发者ID:Rosiak,项目名称:misc,代码行数:35,代码来源:check_eva.py


示例4: run

def run():
    profilelevel = None

    if environ.has_key('PROFILELEVEL'):
        profilelevel = int(environ['PROFILELEVEL'])


    if profilelevel is None:
        TestProgramPyMVPA()
    else:
        profilelines = environ.has_key('PROFILELINES')

        import hotshot, hotshot.stats
        pname = "%s.prof" % sys.argv[0]
        prof = hotshot.Profile(pname, lineevents=profilelines)
        try:
            # actually return values are never setup
            # since unittest.main sys.exit's
            benchtime, stones = prof.runcall( unittest.main )
        except SystemExit:
            pass
        print "Saving profile data into %s" % pname
        prof.close()
        if profilelevel > 0:
            # we wanted to see the summary right here
            # instead of just storing it into a file
            print "Loading profile data from %s" % pname
            stats = hotshot.stats.load(pname)
            stats.strip_dirs()
            stats.sort_stats('time', 'calls')
            stats.print_stats(profilelevel)
开发者ID:Arthurkorn,项目名称:PyMVPA,代码行数:31,代码来源:runner.py


示例5: get_username

def get_username():
    """ Returns the username of the current user. """
    if (environ.has_key("USER")):
        return environ["USER"]
    elif (environ.has_key("USERNAME")):
        return environ["USERNAME"]
    else:
        return "Unknown"
开发者ID:Xicnet,项目名称:burnstation,代码行数:8,代码来源:tools.py


示例6: _getRootEnvSys

    def _getRootEnvSys(self,version,usepython=False):
        """Returns an environment suitable for running Root and sometimes Python."""
        from os.path import join
        from os import environ

        from Ganga.Lib.Root.shared import setEnvironment,findPythonVersion

        rootsys = getrootsys(version)

        rootenv = {}
        #propagate from localhost
        if environ.has_key('PATH'):
            setEnvironment('PATH',environ['PATH'],update=True,environment=rootenv)
        if environ.has_key('LD_LIBRARY_PATH'):
            setEnvironment('LD_LIBRARY_PATH',environ['LD_LIBRARY_PATH'],update=True,environment=rootenv)    

        setEnvironment('LD_LIBRARY_PATH',join(rootsys,'lib'),update=True,environment=rootenv)
        setEnvironment('PATH',join(rootsys,'bin'),update=True,environment=rootenv)
        setEnvironment('ROOTSYS',rootsys,update=False,environment=rootenv)
        logger.debug('Have set Root variables. rootenv is now %s', str(rootenv))

        if usepython:
            # first get from config
            python_version = ''
            try:
                python_version = getConfig('ROOT')['pythonversion']
            except ConfigError, e:
                logger.debug('There was a problem trying to get [ROOT]pythonversion: %s.', e)

            #now try grepping files
            if not python_version:    
                python_version = findPythonVersion(rootsys)

            if (python_version is None):
                logger.warn('Unable to find the Python version needed for Root version %s. See the [ROOT] section of your .gangarc file.', version)
            else:
                logger.debug('Python version found was %s', python_version)
            python_home  = getpythonhome(pythonversion=python_version)
            logger.debug('PYTHONHOME is being set to %s',python_home)

            python_bin = join(python_home,'bin')
            setEnvironment('PATH',python_bin,update=True,environment=rootenv)
            setEnvironment('PYTHONPATH',join(rootsys,'lib'),update=True,environment=rootenv)
            logger.debug('Added PYTHONPATH. rootenv is now %s', str(rootenv))
            
            if join(python_bin,'python') != sys.executable:
            #only try to do all this if the python currently running isn't going to be used
                logger.debug('Using a different Python - %s.', python_home)
                python_lib = join(python_home,'lib')

                import os.path
                if not os.path.exists(python_bin) or not os.path.exists(python_lib):
                    logger.error('The PYTHONHOME specified does not have the expected structure. See the [ROOT] section of your .gangarc file.')
            
                setEnvironment('LD_LIBRARY_PATH',python_lib,update=True,environment=rootenv)
                setEnvironment('PYTHONHOME',python_home,update=False,environment=rootenv)
                setEnvironment('PYTHONPATH',python_lib,update=True,environment=rootenv)
开发者ID:wvengen,项目名称:lgipilot,代码行数:57,代码来源:Root.py


示例7: main

def main():
    # initialize variables from environment
    modulePath = Env.get('PythonSleighModulePath', '')
    logDir = Env.get('PythonSleighLogDir')
    if not logDir or not os.path.isdir(logDir):
        logDir = _TMPDIR
    outfile = Env.get('PythonSleighWorkerOut')
    if outfile:
        outfile = os.path.join(logDir, os.path.split(outfile)[1])
    else:
        outfile = _NULFILE
    Env['PythonSleighLogFile'] = outfile
    verbose = Env.has_key('PythonSleighWorkerOut') and 1 or 0
    nwsName = Env['PythonSleighNwsName']
    nwsHost = Env.get('PythonSleighNwsHost', 'localhost')
    nwsPort = int(Env.get('PythonSleighNwsPort', '8765'))
    if Env.has_key('PythonSleighName'):
        name = Env['PythonSleighName']
        if Env.has_key('PythonSleighID'):
            name = '%[email protected]%s' % (name, Env['PythonSleighID'])
        logger.setName(name)
    logger.logDebug(nwsName, nwsHost, nwsPort)

    nws = NetWorkSpace(nwsName, nwsHost, nwsPort, useUse=True, create=False)
    newProtocol = nws.findTry('version') is not None
    if newProtocol:
        worker_id = nws.fetch('worker_ids')
        Env['PythonSleighRank'] = worker_id

    # create the script file for the worker to execute
    script = '''\
import sys, os
try: os.setpgid(0, 0)
except: pass
try: sys.stdout = sys.stderr = open(%s, 'w', 0)
except: pass
sys.path[1:1] = %s.split(os.pathsep)
from nws.sleigh import cmdLaunch
print "entering worker loop"
cmdLaunch(%d)
''' % (repr(outfile), repr(modulePath), verbose)
    fd, tmpname = tempfile.mkstemp(suffix='.py', prefix='__nws', text=True)
    tmpfile = os.fdopen(fd, 'w')
    tmpfile.write(script)
    tmpfile.close()

    logger.logDebug("executing Python worker")
    argv = [sys.executable, tmpname]
    out = open(outfile, 'w')

    try:
        p = subprocess.Popen(argv, stdin=open(tmpname), stdout=out,
                stderr=subprocess.STDOUT)
    except OSError, e:
        logger.logError("error executing command:", argv)
        raise e
开发者ID:bigcomputing,项目名称:python-big,代码行数:56,代码来源:PythonNWSSleighWorker.py


示例8: main

def main():
	try:
		global keep_running, password, port, libraryFileLocation
		keep_running = True
		
		nextIsPass = False
		nextIsPort = False
		
		if environ.has_key('TC_PORT'):
			port = int(environ['TC_PORT'])
			del environ['TC_PORT']
		
		if environ.has_key('TC_PASSWORD'):
			password = environ['TC_PASSWORD'][:]
			del environ['TC_PASSWORD']
		
		for arg in sys.argv:
			if arg == "--password":
				nextIsPass = True
			elif arg == "--port":
				nextIsPort = True
			elif nextIsPass:
				password = arg
				nextIsPass = False
			elif nextIsPort:
				port = int(arg)
				nextIsPort = False
		
		server = HTTPServer(('', port), TCHandler)
		print 'started httpserver...'
		bonjourService = pybonjour.DNSServiceRegister(
			name = socket.gethostname().replace('.local', ''),
			regtype = '_tunage._tcp',
			port = port)
		
		loadLibraryFile(libraryFileLocation)
		while keep_running:
			server.handle_request()
			
		print 'termination command received, shutting down server'
		server.socket.close()
		bonjourService.close()
		return
	except KeyboardInterrupt, SystemExit:
		print 'termination command received, shutting down server'
		server.socket.close()
		bonjourService.close()
		return
开发者ID:13bold,项目名称:TuneConnect,代码行数:48,代码来源:tc-server-old.py


示例9: foamMPI

def foamMPI():
    """@return: the used MPI-Implementation"""
    if not environ.has_key("WM_MPLIB"):
        return ()
    else:
        vStr=environ["WM_MPLIB"]
        return vStr
开发者ID:floli,项目名称:tools,代码行数:7,代码来源:FoamInformation.py


示例10: find_executable

def find_executable(executable_name):
    """Helper function to find executables"""
    from os import path, name, environ, pathsep
    from sys import argv

    executable_name = path.basename(executable_name)
    logger.debug("Looking for executable {}".format(executable_name))
    if name == "nt":
        executable_name += ".exe"
    possible_locations = environ["PATH"].split(pathsep) if environ.has_key("PATH") else []
    possible_locations.insert(0, path.dirname(argv[0]))
    if name == "nt":
        possible_locations.append(path.join(r"C:", "Windows", "System32"))
    else:
        possible_locations += [
            path.join(path.sep, "sbin"),
            path.join(path.sep, "usr", "bin"),
            path.join(path.sep, "bin"),
        ]
    possible_executables = [path.join(location, executable_name) for location in possible_locations]
    existing_executables = [item for item in possible_executables if path.exists(item)]
    if not existing_executables:
        logger.debug("No executables found")
        return executable_name
    logger.debug("Found the following executables: {}".format(existing_executables))
    return existing_executables[0]
开发者ID:Infinidat,项目名称:infi.logs_collector,代码行数:26,代码来源:__init__.py


示例11: __init__

    def __init__(self, co, user, server, txn):
        self.co       = co
        self.user     = user
        self.server   = server
        self.txn      = txn

        self.secret_key    = "secret-%s-%s" % (user, server)
        self.hash_key      = 'hash-%s-%s'   % (user, server)
        self.pwid_key      = "pwid-%s-%s"   % (user, server)

        self.password = None
        self.secret   = None
        self.pwid     = co.linforepo.get(self.pwid_key, txn=txn)

        self.agent_sock   = None
        try:
            if environ.has_key('CDV_AUTH_SOCK'):
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                sock.connect(environ['CDV_AUTH_SOCK'])
                self.agent_sock = sock
            elif co.nopass == 2:
                raise ValueError, 'No agent found'
        except socket.error:
            if co.nopass == 2:
                raise
        return
开发者ID:GymWenFLL,项目名称:tpp_libs,代码行数:26,代码来源:auth.py


示例12: get_level

def get_level():
    from os import environ

    if environ.has_key('SS_LOG_LEVEL'):
        return getattr(logging, environ.get('SS_LOG_LEVEL'))
    else:
        return logging.DEBUG
开发者ID:gipi,项目名称:Streamstudio,代码行数:7,代码来源:sslog.py


示例13: getcookie

def getcookie(key):
    if environ.has_key('HTTP_COOKIE'):
       for cookie in environ['HTTP_COOKIE'].split(';'):
            k , v = cookie.split('=')
            if key == k:
                return v
    return ""
开发者ID:0x24bin,项目名称:WebShell-1,代码行数:7,代码来源:pyspy.py


示例14: check_version

def check_version() :
  if environ.has_key('SMDS_URL') :
    from smds.version import version
    from urllib import urlopen, urlretrieve
    import tarfile
    try:
      repository_version = urlopen(environ['SMDS_URL']+'.version').readline()
    except: return
    if version != repository_version.strip() :
      stop()
      if platform == 'win32' :
        from win32api import SearchPath
        from win32process import CreateProcess, STARTUPINFO
        (path, d) = SearchPath(None, 'python', '.exe')
        CreateProcess(path, 'python %s\\smds\\downloader.py' % 
        		environ['SMDS_LOC'],
    			None, None, 0,
                            0, None, None, STARTUPINFO())
        exit()
      else:
        try :
          fn = urlretrieve(environ['SMDS_URL'])[0]
          f = tarfile.open(fn, 'r:gz')
          for m in f.getmembers() :
            f.extract(m, environ['SMDS_LOC'])
        except : return
开发者ID:bryon-drown,项目名称:SMDS,代码行数:26,代码来源:starter.py


示例15: getEnviron

 def getEnviron(self,name):
     """@param name: name of an environment variable
     @return: value of the variable, empty string if non-existing"""
     result=""
     if environ.has_key(name):
         result=environ[name]
     return result
开发者ID:floli,项目名称:tools,代码行数:7,代码来源:FoamServer.py


示例16: foamVersionString

def foamVersionString(useConfigurationIfNoInstallation=False):
    """@return: string for the  Foam-version as found
    in $WM_PROJECT_VERSION"""
    
    if not environ.has_key("WM_PROJECT_VERSION") and not useConfigurationIfNoInstallation:
        return ""
    else:
        if environ.has_key("WM_PROJECT_VERSION"):
            vStr=environ["WM_PROJECT_VERSION"]
        else:
            vStr=""
            
        if vStr=="" and  useConfigurationIfNoInstallation:
            vStr=config().get("OpenFOAM","Version")

    return vStr
开发者ID:floli,项目名称:tools,代码行数:16,代码来源:FoamInformation.py


示例17: format_buffer

def format_buffer(ebuf, col=60):
    """Format the text buffer 'ebuf'.

    Parameter 'ebuf' is as a list of strings. The text displayed will use a
    column width no more than the value stored in the environment variable
    COLUMNS if available. Otherwise a conservative width of no more than 60
    characters will be used.
    """
    if environ.has_key('COLUMNS'):
        txtwid = int(environ['COLUMNS']) - 2
    else:
        txtwid = col - 2
    if len(ebuf) == 0: return ""
    final = []
    while len(ebuf) > 0:
        (line, rem) = string_truncate(ebuf[0], txtwid)
        ebuf = ebuf[1:]
        final.append("{0:s}".format(line))
        while len(rem) > txtwid:
            (line, rem) = string_truncate(rem, txtwid)
            final.append("{0:s}".format(line))
        final.append("{0:s}".format(rem))
    text = final[0]
    if not text.endswith('\n'): text += '\n'
    for line in final[1:]:
        if not line.endswith('\n'): line += '\n'
        text += '> ' + line
    return text
开发者ID:tsinclair,项目名称:PyDeskAPI,代码行数:28,代码来源:__init__.py


示例18: __init__

    def __init__(self, name='sid', dir=path_join(WORK_DIR, 'sessions'),
            path=None, domain=None, max_age=None):

        self._name = name
        now = datetime.utcnow();

        # blank cookie
        self._cookie = SimpleCookie()

        if environ.has_key('HTTP_COOKIE'):
            # cookie already exists, see what's in it
            self._cookie.load(environ['HTTP_COOKIE'])

        try:
            # what's our session ID?
            self.sid = self._cookie[name].value;
        except KeyError:
            # there isn't any, make a new session ID
            remote = environ.get('REMOTE_ADDR')
            self.sid = sha224('%s-%s' % (remote, now)).hexdigest()

        self._cookie.clear();
        self._cookie[name] = self.sid

        # set/reset path
        if path:
            self._cookie[name]['path'] = path
        else:
            self._cookie[name]['path'] = ''

        # set/reset domain
        if domain:
            self._cookie[name]['domain'] = domain
        else:
            self._cookie[name]['domain'] = ''

        # set/reset expiration date
        if max_age:
            if isinstance(max_age, int):
                max_age = timedelta(seconds=max_age)
            expires = now + max_age
            self._cookie[name]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
        else:
            self._cookie[name]['expires'] = ''

        # to protect against cookie-stealing JS, make our cookie
        # available only to the browser, and not to any scripts
        try:
            # This will not work for Python 2.5 and older
            self._cookie[name]['httponly'] = True
        except CookieError:
            pass

        # if the sessions dir doesn't exist, create it
        if not exists(dir):
            mkdir(dir)
        # persist the session data
        self._shelf_file = path_join(dir, self.sid)
        # -1 signifies the highest available protocol version
        self._shelf = shelve_open(self._shelf_file, protocol=-1, writeback=True)
开发者ID:dmcc,项目名称:brat,代码行数:60,代码来源:session.py


示例19: getCPPCookies

        def getCPPCookies(self):
                if environ.has_key('HTTP_COOKIE'):
                        #s('reading cookies from server...\n')
                        #for eachCookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
                        cookies = [x.strip() for x in environ['HTTP_COOKIE'].split(';')]
                        for eachCookie in cookies:
                                if len(eachCookie) > 6 and eachCookie[:3] == 'CPP':
                                        tag = eachCookie[3:7]
                                        try:
                                                self.cookies[tag] = eval(unquote(eachCookie[8:]))
                                        except (NameError, SyntaxError):
                                                self.cookies[tag] = unquote(eachCookie[8:])
                        if not self.cookies.has_key('info'):
                            self.cookies['info'] = ''
                        if not self.cookies.has_key('user'):
                            self.cookies['user'] = ''
                else:
                        #s('no cookies on server...\n')
                        self.cookies['info'] = self.cookies['user'] = ''

                #s('cookies: %s\n' % str(self.cookies))
                if self.cookies['info'] != '':
                        self.who, langStr, self.fn = self.cookies['info'].split(':')
                        self.langs = langStr.split(',')
                else:
                        self.who = self.fn = ''
                        self.langs = ['Python']
开发者ID:EnTeQuAk,项目名称:pydanny-event-notes,代码行数:27,代码来源:advcgi2.py


示例20: newPlayer

 def newPlayer(self):
     self._player = gst.element_factory_make("playbin", "player")
     if environ.has_key("GST_AUDIO_SINK"):
         sink = environ["GST_AUDIO_SINK"]
         self._sink = gst.element_factory_make(sink, "custom-audio-sink " + sink)
         self._sink.set_property("sync", True)
         self._player.set_property("audio-sink", self._sink)
开发者ID:Ferada,项目名称:nih,代码行数:7,代码来源:player.py



注:本文中的os.environ.has_key函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python environ.items函数代码示例发布时间:2022-05-25
下一篇:
Python environ.get函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap