本文整理汇总了Python中os.environ.has_key函数的典型用法代码示例。如果您正苦于以下问题:Python has_key函数的具体用法?Python has_key怎么用?Python has_key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了has_key函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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,
)
示例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]
示例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)
示例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)
示例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"
示例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)
示例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
示例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
示例9: foamMPI
def foamMPI():
"""@return: the used MPI-Implementation"""
if not environ.has_key("WM_MPLIB"):
return ()
else:
vStr=environ["WM_MPLIB"]
return vStr
示例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]
示例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
示例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
示例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 ""
示例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
示例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