本文整理汇总了Python中os.environ.items函数的典型用法代码示例。如果您正苦于以下问题:Python items函数的具体用法?Python items怎么用?Python items使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了items函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_cron
def test_cron():
fileobj = open('/home/robouser/cron_test.dat','w')
t = datetime.utcnow()
fileobj.write( t.strftime("%Y-%m-%dT%H:%M:%S") + '\n' )
fileobj.write('Completed imports\n')
fileobj.flush()
config = { 'k2_footprint_data': \
'/home/robouser/Software/robonet_site/data/k2-footprint.json',
'xsuperstamp_target_data': \
'/home/robouser/Software/robonet_site/data/xsuperstamp_targets.json',
'ddt_target_data': \
'/home/robouser/Software/robonet_site/data/c9-ddt-targets-preliminary.csv',
'tmp_location': \
'/science/robonet/rob/Operations/ExoFOP', \
'k2_campaign': 9, \
'k2_year': 2016, \
'log_directory': '/science/robonet/rob/Operations/ExoFOP', \
'log_root_name': 'test_cron'
}
fileobj.write('Set up config\n')
log = log_utilities.start_day_log( config, __name__, console=False )
fileobj.write('Started logging\n')
log.info('Started logging')
environ['DISPLAY'] = ':99'
environ['PWD'] = '/science/robonet/rob/Operations/ExoFOP/'
chdir(environ['PWD'])
log.info(str(environ.items()))
fileobj.write( str(environ.items())+ '\n')
#pkg_path = '/opt/anaconda.2.5.0/bin/K2onSilicon'
#chdir('/science/robonet/rob/Operations/ExoFOP')
#target_file = 'target.csv'
#output_file = '/science/robonet/rob/Operations/ExoFOP/targets_siliconFlag.cav'
comm = '/opt/anaconda.2.5.0/bin/K2onSilicon /science/robonet/rob/Operations/ExoFOP/target.csv 9'
#( iexec, coutput ) = getstatusoutput( pkg_path + ' ' + target_file + \
# ' ' + str(config['k2_campaign']) )
( iexec, coutput ) = getstatusoutput( comm )
log.info(coutput + '\n')
log.info('Loaded K2 data')
fileobj.write(coutput + '\n')
fileobj.write('Loaded K2 Campaign data\n')
fileobj.flush()
fileobj.close()
log_utilities.end_day_log( log )
开发者ID:ytsapras,项目名称:robonet_site,代码行数:48,代码来源:test_cron.py
示例2: feed_init
def feed_init(self, *args, **kwargs):
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Fetch Script Specific Arguments
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
feedid = kwargs.get('feedid')
filename = kwargs.get('filename')
# Fetch/Load Feed Script Configuration
script_config = dict([(FEED_OPTS_RE.match(k).group(1), v.strip()) \
for (k, v) in environ.items() if FEED_OPTS_RE.match(k)])
if self.vvdebug:
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Print Global Script Varables to help debugging process
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
for k, v in script_config.items():
self.logger.vvdebug('%s%s=%s' % (FEED_ENVIRO_ID, k, v))
# Merge Script Configuration With System Config
self.system = dict(script_config.items() + self.system.items())
# self.feedid
# This is the Feed Identifier passed in from NZBGet
if feedid is None:
self.feedid = environ.get(
'%sFEEDID' % FEED_ENVIRO_ID,
)
else:
self.feedid = feedid
# self.filename
# This is the Feed Filename passed in from NZBGet
if filename is None:
self.filename = environ.get(
'%sFILENAME' % FEED_ENVIRO_ID,
)
else:
self.filename = filename
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Error Handling
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
try:
self.feedid = int(self.feedid)
self.logger.info('Feed ID assigned: %d' % self.feedid)
except (ValueError, TypeError):
# Default is 0
self.feedid = 0
self.logger.warning('No Feed ID was assigned')
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Enforce system/global variables for script processing
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
self.system['FEEDID'] = self.feedid
if isinstance(self.feedid, int) and self.feedid > 0:
environ['%sFEEDID' % FEED_ENVIRO_ID] = str(self.feedid)
self.system['FILENAME'] = self.filename
if self.filename:
environ['%sFILENAME' % FEED_ENVIRO_ID] = self.filename
开发者ID:Anthrow,项目名称:nzbget-subliminal,代码行数:60,代码来源:FeedScript.py
示例3: setbg
def setbg(imghash):
img = join(IMG_PATH, imghash+'.'+CONFIG['IMG_EXT'])
env = dict(environ.items() + {'DISPLAY': CONFIG['DISPLAY']}.items())
if isfile(img):
call(['feh', '--bg-max', img], env=env)
else:
logging.warn('Cannot find image: %s' % img)
开发者ID:webgetpics,项目名称:webgetpics,代码行数:7,代码来源:show.py
示例4: load_config
def load_config(self):
"""
For now just load all uppercase options from the
environment.
"""
for option, value in environ.items():
if option.isupper():
setattr(self, option, value)
开发者ID:alexex,项目名称:hackzurich,代码行数:8,代码来源:config.py
示例5: get_env
def get_env(self):
include_dirs = [
"-I{}/{}".format(
self.ctx.include_dir,
d.format(arch=self))
for d in self.ctx.include_dirs]
env = {}
ccache = sh.which('ccache')
cc = sh.xcrun("-find", "-sdk", self.sdk, "clang").strip()
if ccache:
ccache = ccache.strip()
use_ccache = environ.get("USE_CCACHE", "1")
if use_ccache != '1':
env["CC"] = cc
else:
if not self._ccsh:
self._ccsh = ccsh = sh.mktemp().strip()
with open(ccsh, 'w') as f:
f.write('#!/bin/sh\n')
f.write(ccache + ' ' + cc + ' "[email protected]"\n')
sh.chmod('+x', ccsh)
else:
ccsh = self._ccsh
env["USE_CCACHE"] = '1'
env["CCACHE"] = ccache
env["CC"] = ccsh
env.update({k: v for k, v in environ.items() if k.startswith('CCACHE_')})
env.setdefault('CCACHE_MAXSIZE', '10G')
env.setdefault('CCACHE_HARDLINK', 'true')
env.setdefault('CCACHE_SLOPPINESS', ('file_macro,time_macros,'
'include_file_mtime,include_file_ctime,file_stat_matches'))
else:
env["CC"] = cc
env["AR"] = sh.xcrun("-find", "-sdk", self.sdk, "ar").strip()
env["LD"] = sh.xcrun("-find", "-sdk", self.sdk, "ld").strip()
env["OTHER_CFLAGS"] = " ".join(include_dirs)
env["OTHER_LDFLAGS"] = " ".join([
"-L{}/{}".format(self.ctx.dist_dir, "lib"),
])
env["CFLAGS"] = " ".join([
"-arch", self.arch,
"-pipe", "-no-cpp-precomp",
"--sysroot", self.sysroot,
#"-I{}/common".format(self.ctx.include_dir),
#"-I{}/{}".format(self.ctx.include_dir, self.arch),
"-O3",
self.version_min
] + include_dirs)
env["LDFLAGS"] = " ".join([
"-arch", self.arch,
"--sysroot", self.sysroot,
"-L{}/{}".format(self.ctx.dist_dir, "lib"),
"-lsqlite3",
self.version_min
])
return env
开发者ID:cbenhagen,项目名称:kivy-ios,代码行数:58,代码来源:toolchain.py
示例6: checkOSEnviron
def checkOSEnviron(self,handler):
empty = {}; setup_testing_defaults(empty)
env = handler.environ
from os import environ
for k,v in environ.items():
if not empty.has_key(k):
self.assertEqual(env[k],v)
for k,v in empty.items():
self.failUnless(env.has_key(k))
开发者ID:amcgregor,项目名称:wsgi2,代码行数:9,代码来源:tests.py
示例7: checkOSEnviron
def checkOSEnviron(self,handler):
empty = {}; setup_testing_defaults(empty)
env = handler.environ
from os import environ
for k,v in environ.items():
if k not in empty:
self.assertEqual(env[k],v)
for k,v in empty.items():
self.assertIn(k, env)
开发者ID:524777134,项目名称:cpython,代码行数:9,代码来源:test_wsgiref.py
示例8: get_db_url
def get_db_url():
"""
Attempt to find any possible database configuration URL
Datica: DATABASE_1_URL
Heroku: DATABASE_URL
"""
candidate_db_envvars = (
value for name, value in environ.items()
if 'DATABASE' in name and value
)
# Return None if no candidates found
return next(candidate_db_envvars, None)
开发者ID:ivan-c,项目名称:true_nth_usa_portal,代码行数:13,代码来源:remap_envvars.py
示例9: __exit
def __exit(exit_code):
from os import environ
__env__new__items = environ.items()
global __env__old__items
k_v = [(k, v)
for (k, v) in __env__new__items if (k, v) not in __env__old__items]
__env__file = open(environ[ENV_FILE_NAME], 'w')
for k, v in k_v:
__env__file.write('%s=%s\n' % (k, json.dumps(v)))
__env__file.close()
del __env__old__items
del __env__new__items
exit(exit_code)
开发者ID:voreshkov,项目名称:cloudrunner,代码行数:14,代码来源:functions.py
示例10: format_message
def format_message(type, value, traceback):
message = StringIO()
out = lambda m: message.write(u'{}\n'.format(m))
out(ctime())
out('== Traceback ==')
out(''.join(format_exception(type, value, traceback)))
out('\n== Command line ==')
out(' '.join(sys.argv))
out('\n== Environment ==')
for key, value in environ.items():
out('{} = {}'.format(key, value))
return message.getvalue()
开发者ID:tebeka,项目名称:pythonwise,代码行数:14,代码来源:crashlog.py
示例11: submit_job
def submit_job():
opts = [
["--{}".format(key[4:].replace("_", "-")), value]
for key, value in environ.items()
if key.startswith("TBV_") and key != "TBV_CLASS"
]
command = [
"spark-submit",
"--master", "yarn",
"--deploy-mode", "client",
"--class", environ["TBV_CLASS"],
artifact_file,
] + [v for opt in opts for v in opt if v]
call_exit_errors(command)
开发者ID:mozilla,项目名称:telemetry-airflow,代码行数:16,代码来源:telemetry_batch_view.py
示例12: index
def index():
response.content_type = 'text/plain; charset=utf-8'
ret = 'Hello world, I\'m %s!\n\n' % os.getpid()
ret += 'Request vars:\n'
for k, v in request.environ.items():
if 'bottle.' in k:
continue
ret += '%s=%s\n' % (k, v)
ret += '\n'
ret += 'Environment vars:\n'
for k, v in env.items():
if 'bottle.' in k:
continue
ret += '%s=%s\n' % (k, v)
return ret
开发者ID:nakaly,项目名称:HelloWorld,代码行数:18,代码来源:app.py
示例13: get_command_output
def get_command_output(*command_line):
"""Execute a command line, and return its output.
Raises an exception if return value is nonzero.
:param *command_line: Words for the command line. No shell expansions
are performed.
:type *command_line: Sequence of basestring.
:return: Output from the command.
:rtype: List of basestring, one per line.
"""
env = {
variable: value
for variable, value in environ.items()
if not variable.startswith('LC_')}
env.update({
'LC_ALL': 'C',
'LANG': 'en_US.UTF-8',
})
return check_output(command_line, env=env).splitlines()
开发者ID:deepakhajare,项目名称:maas,代码行数:20,代码来源:address.py
示例14: dump_environment
def dump_environment(to_var=False):
"""
Dump the shell's env vars to stdout as JSON document.
Args:
to_var (boolean): also dump the env vars to /var?
"""
print(
json.dumps({k: os.environ[k] for k in os.environ.keys()},
indent=4,
sort_keys=True))
if to_var:
try:
with open('env.sh', 'w') as env_log:
env_log.write("# {}\n".format(time.strftime("%c")))
for key, value in environ.items():
env_log.write('export {}="{}"\n'.format(key, value))
except IOError as e:
log_and_stdout(str(e))
log_and_stdout("Failed to create env.sh in cookbook dir...")
开发者ID:Nextdoor,项目名称:rightscale_rightlink10_rightscripts,代码行数:21,代码来源:__init__.py
示例15: create_app
def create_app(config):
from os import environ
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_pyfile(config)
app.config.update({
key: val
for key, val in environ.items()
if key.startswith("STAFF") and key.isupper()
})
db.init_app(app)
from .ext import admin, cache, security
# init admin
admin.init_app(app)
# init cache
cache.init_app(app)
# init security
from .account.models import User, Role
from flask.ext.security import SQLAlchemyUserDatastore, login_required
datastore = SQLAlchemyUserDatastore(db, User, Role)
security.init_app(app, datastore)
from . import account, wechat, gitlab
account.init_app(app)
wechat.init_app(app)
gitlab.init_app(app)
account.init_admin()
wechat.init_admin()
gitlab.init_admin()
@app.route("/")
def index():
return render_template("index.html")
return app
开发者ID:SkyLothar,项目名称:staff,代码行数:40,代码来源:__init__.py
示例16: get_options
def get_options(self):
"""Returns dictionary with application variables from system environment.
Application variables start with {app_} prefix,
but in returned dictionary is set without this prefix.
#!ini
poor_LogLevel = warn # Poor WSGI variable
app_db_server = localhost # application variable db_server
app_templates = app/templ # application variable templates
This method works like Request.get_options, but work with
os.environ, so it works only with wsgi servers, which set not only
request environ, but os.environ too. Apaches mod_wsgi don't do that,
uWsgi and PoorHTTP do that.
"""
options = {}
for key, val in environ.items():
key = key.strip()
if key[:4].lower() == 'app_':
options[key[4:].lower()] = val.strip()
return options
开发者ID:PoorHttp,项目名称:PoorWSGI,代码行数:22,代码来源:wsgi.py
示例17: get_feed
def get_feed(self, feedid=None):
"""Returns a dictionary of feed details identified by the id
specified. If no id is specified, then the current feed is
detected and returned.
"""
if feedid is None:
# assume default
feedid = self.feedid
if not isinstance(feedid, int):
try:
feedid = int(feedid)
except (ValueError, TypeError):
# can't be typecasted to an integer
return {}
if feedid <= 0:
# No feed id defined
return {}
# Precompile Regulare Expression for Speed
feed_re = re.compile('^%s%s%d_([A-Z0-9_]+)$' % (
FEED_ENVIRO_ID,
FEEDID_ENVIRO_ID,
feedid,
))
self.logger.debug('Looking for %s%s%d_([A-Z0-9_]+)$' % (
FEED_ENVIRO_ID,
FEEDID_ENVIRO_ID,
feedid,
))
# Fetch Feed related content
return dict([(feed_re.match(k).group(1), v.strip()) \
for (k, v) in environ.items() if feed_re.match(k)])
开发者ID:Anthrow,项目名称:nzbget-subliminal,代码行数:36,代码来源:FeedScript.py
示例18: cgi_app_runner
def cgi_app_runner(app):
""" Runs "app" in a CGI environment.
CGI example script
==================
>>> import cgitb; cgitb.enable()
>>> import sys
>>> from enkel.wansgli.cgigateway import cgi_app_runner
>>> from enkel.wansgli.demo_apps import simple_app
>>> cgi_app_runner(simple_app)
Put the above in a executable python script, and run it using
a cgi server.
@note: This code is almost a copy of the CGI gateway example in
PEP 333. It will be replaced by a more powerfull class
that supports logging ++ in the future.
@param app: A WSGI app.
"""
env = dict(environ.items())
env['wsgi.input'] = sys.stdin
env['wsgi.errors'] = sys.stderr
env['wsgi.version'] = (1,0)
env['wsgi.multithread'] = False
env['wsgi.multiprocess'] = True
env['wsgi.run_once'] = True
if env.get('HTTPS','off') in ('on','1'):
env['wsgi.url_scheme'] = 'https'
else:
env['wsgi.url_scheme'] = 'http'
req = Response(sys.stdout, env)
run_app(app, req)
开发者ID:espenak,项目名称:enkel,代码行数:36,代码来源:cgigateway.py
示例19: dict
import sys
import logging
import mock
import argparse
import subprocess
from os import curdir, makedirs, chdir, environ
from os.path import join, curdir, dirname
from shlex import split as shlex_split
from textwrap import dedent
from functools import partial
from bumpversion import main, DESCRIPTION
SUBPROCESS_ENV = dict(
list(environ.items()) + [('HGENCODING', 'utf-8')]
)
call = partial(subprocess.call, env=SUBPROCESS_ENV)
check_call = partial(subprocess.check_call, env=SUBPROCESS_ENV)
check_output = partial(subprocess.check_output, env=SUBPROCESS_ENV)
xfail_if_no_git = pytest.mark.xfail(
call(["git", "--help"], shell=True) != 1,
reason="git is not installed"
)
xfail_if_no_hg = pytest.mark.xfail(
call(["hg", "--help"], shell=True) != 0,
reason="hg is not installed"
)
开发者ID:Mondego,项目名称:pyreco,代码行数:31,代码来源:allPythonContent.py
示例20: get_env
def get_env(self, with_flags_in_cc=True, clang=False):
env = {}
cflags = [
'-DANDROID',
'-fomit-frame-pointer',
'-D__ANDROID_API__={}'.format(self.ctx.ndk_api)]
if not clang:
cflags.append('-mandroid')
else:
cflags.append('-target ' + self.target)
toolchain = '{android_host}-{toolchain_version}'.format(
android_host=self.ctx.toolchain_prefix,
toolchain_version=self.ctx.toolchain_version)
toolchain = join(self.ctx.ndk_dir, 'toolchains', toolchain,
'prebuilt', build_platform)
cflags.append('-gcc-toolchain {}'.format(toolchain))
env['CFLAGS'] = ' '.join(cflags)
# Link the extra global link paths first before anything else
# (such that overriding system libraries with them is possible)
env['LDFLAGS'] = ' ' + " ".join([
"-L'" + l.replace("'", "'\"'\"'") + "'" # no shlex.quote in py2
for l in self.extra_global_link_paths
]) + ' '
sysroot = join(self.ctx._ndk_dir, 'sysroot')
if exists(sysroot):
# post-15 NDK per
# https://android.googlesource.com/platform/ndk/+/ndk-r15-release/docs/UnifiedHeaders.md
env['CFLAGS'] += ' -isystem {}/sysroot/usr/include/{}'.format(
self.ctx.ndk_dir, self.ctx.toolchain_prefix)
env['CFLAGS'] += ' -I{}/sysroot/usr/include/{}'.format(
self.ctx.ndk_dir, self.command_prefix)
else:
sysroot = self.ctx.ndk_platform
env['CFLAGS'] += ' -I{}'.format(self.ctx.ndk_platform)
env['CFLAGS'] += ' -isysroot {} '.format(sysroot)
env['CFLAGS'] += '-I' + join(self.ctx.get_python_install_dir(),
'include/python{}'.format(
self.ctx.python_recipe.version[0:3])
)
env['LDFLAGS'] += '--sysroot={} '.format(self.ctx.ndk_platform)
env["CXXFLAGS"] = env["CFLAGS"]
env["LDFLAGS"] += " ".join(['-lm', '-L' + self.ctx.get_libs_dir(self.arch)])
if self.ctx.ndk == 'crystax':
env['LDFLAGS'] += ' -L{}/sources/crystax/libs/{} -lcrystax'.format(self.ctx.ndk_dir, self.arch)
toolchain_prefix = self.ctx.toolchain_prefix
toolchain_version = self.ctx.toolchain_version
command_prefix = self.command_prefix
env['TOOLCHAIN_PREFIX'] = toolchain_prefix
env['TOOLCHAIN_VERSION'] = toolchain_version
ccache = ''
if self.ctx.ccache and bool(int(environ.get('USE_CCACHE', '1'))):
# print('ccache found, will optimize builds')
ccache = self.ctx.ccache + ' '
env['USE_CCACHE'] = '1'
env['NDK_CCACHE'] = self.ctx.ccache
env.update({k: v for k, v in environ.items() if k.startswith('CCACHE_')})
if clang:
llvm_dirname = split(
glob(join(self.ctx.ndk_dir, 'toolchains', 'llvm*'))[-1])[-1]
clang_path = join(self.ctx.ndk_dir, 'toolchains', llvm_dirname,
'prebuilt', build_platform, 'bin')
environ['PATH'] = '{clang_path}:{path}'.format(
clang_path=clang_path, path=environ['PATH'])
exe = join(clang_path, 'clang')
execxx = join(clang_path, 'clang++')
else:
exe = '{command_prefix}-gcc'.format(command_prefix=command_prefix)
execxx = '{command_prefix}-g++'.format(command_prefix=command_prefix)
cc = find_executable(exe, path=environ['PATH'])
if cc is None:
print('Searching path are: {!r}'.format(environ['PATH']))
raise BuildInterruptingException(
'Couldn\'t find executable for CC. This indicates a '
'problem locating the {} executable in the Android '
'NDK, not that you don\'t have a normal compiler '
'installed. Exiting.'.format(exe))
if with_flags_in_cc:
env['CC'] = '{ccache}{exe} {cflags}'.format(
exe=exe,
ccache=ccache,
cflags=env['CFLAGS'])
env['CXX'] = '{ccache}{execxx} {cxxflags}'.format(
execxx=execxx,
ccache=ccache,
cxxflags=env['CXXFLAGS'])
else:
#.........这里部分代码省略.........
开发者ID:PKRoma,项目名称:python-for-android,代码行数:101,代码来源:archs.py
注:本文中的os.environ.items函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论