本文整理汇总了Python中os.getenv方法的典型用法代码示例。如果您正苦于以下问题:Python os.getenv方法的具体用法?Python os.getenv怎么用?Python os.getenv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.getenv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _update_params_on_kvstore_nccl
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names):
"""Perform update of param_arrays from grad_arrays on NCCL kvstore."""
valid_indices = [index for index, grad_list in
enumerate(grad_arrays) if grad_list[0] is not None]
valid_grad_arrays = [grad_arrays[i] for i in valid_indices]
valid_param_arrays = [param_arrays[i] for i in valid_indices]
valid_param_names = [param_names[i] for i in valid_indices]
size = len(valid_grad_arrays)
start = 0
# Use aggregation by default only with NCCL
default_batch = '16'
batch = int(os.getenv('MXNET_UPDATE_AGGREGATION_SIZE', default_batch))
while start < size:
end = start + batch if start + batch < size else size
# push gradient, priority is negative index
kvstore.push(valid_param_names[start:end], valid_grad_arrays[start:end], priority=-start)
# pull back the weights
kvstore.pull(valid_param_names[start:end], valid_param_arrays[start:end], priority=-start)
start = end
示例2: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def __init__(self):
self._logger = Util.get_logger('SPOT.COMMON.KERBEROS')
principal, keytab, sasl_mech, security_proto = config.kerberos()
if os.getenv('KINITPATH'):
self._kinit = os.getenv('KINITPATH')
else:
self._kinit = "kinit"
self._kinitopts = os.getenv('KINITOPTS')
self._keytab = "-kt {0}".format(keytab)
self._krb_user = principal
if self._kinit == None or self._keytab == None or self._krb_user == None:
self._logger.error("Please verify kerberos configuration, some environment variables are missing.")
sys.exit(1)
if self._kinitopts is None:
self._kinit_cmd = "{0} {1} {2}".format(self._kinit, self._keytab, self._krb_user)
else:
self._kinit_cmd = "{0} {1} {2} {3}".format(self._kinit, self._kinitopts, self._keytab, self._krb_user)
示例3: get_emsdk_root
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def get_emsdk_root():
# Shamelessly copied from Godot's detect.py
em_config_file = os.getenv('EM_CONFIG') or os.path.expanduser('~/.emscripten')
if not os.path.exists(em_config_file):
raise BuildError("Emscripten configuration file '%s' does not exist" % em_config_file)
with open(em_config_file) as f:
em_config = {}
try:
# Emscripten configuration file is a Python file with simple assignments.
exec(f.read(), em_config)
except StandardError as e:
raise BuildError("Emscripten configuration file '%s' is invalid:\n%s" % (em_config_file, e))
if 'BINARYEN_ROOT' in em_config and os.path.isdir(os.path.join(em_config.get('BINARYEN_ROOT'), 'emscripten')):
# New style, emscripten path as a subfolder of BINARYEN_ROOT
return os.path.join(em_config.get('BINARYEN_ROOT'), 'emscripten')
elif 'EMSCRIPTEN_ROOT' in em_config:
# Old style (but can be there as a result from previous activation, so do last)
return em_config.get('EMSCRIPTEN_ROOT')
else:
raise BuildError("'BINARYEN_ROOT' or 'EMSCRIPTEN_ROOT' missing in Emscripten configuration file '%s'" % em_config_file)
示例4: run_trigger
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def run_trigger(name, bundleid=None, arg=None):
"""Call an Alfred External Trigger.
.. versionadded:: 1.31
If ``bundleid`` is not specified, reads the bundle ID of the current
workflow from Alfred's environment variables.
Args:
name (str): Name of External Trigger to call.
bundleid (str, optional): Bundle ID of workflow trigger belongs to.
arg (str, optional): Argument to pass to trigger.
"""
if not bundleid:
bundleid = os.getenv('alfred_workflow_bundleid')
if arg:
arg = 'with argument "{}"'.format(applescriptify(arg))
else:
arg = ''
script = AS_TRIGGER.format(name=name, bundleid=bundleid,
arg=arg)
run_applescript(script)
示例5: main
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def main(wf):
query = sys.argv[1]
baseUrl = os.getenv('baseUrl')
url = baseUrl + 'user?keyword=' + query
try:
result = web.get(url=url)
result.raise_for_status()
resp = result.text
userList = json.loads(resp)
if len(userList) > 0:
for item in userList:
title = item['title']
subtitle = item['subTitle']
icon = item['icon']
userId = item['userId']
copyText = item['copyText']
qlurl = item['url']
wf.add_item(title=title, subtitle=subtitle, icon=icon, largetext=title, copytext=copyText, quicklookurl=qlurl, arg=userId, valid=True)
else:
wf.add_item(title='找不到联系人…',subtitle='请重新输入')
except IOError:
wf.add_item(title='请先启动微信 & 登录…',subtitle='并确保安装微信小助手')
wf.send_feedback()
示例6: load_libmkl
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def load_libmkl():
if os.name == 'posix':
try:
lib_mkl = os.getenv('LIBMKL')
return _ctypes.cdll.LoadLibrary(lib_mkl)
except:
pass
try:
return _ctypes.cdll.LoadLibrary("libmkl_rt.dylib")
except:
raise ValueError('MKL Library not found')
else:
try:
return _ctypes.cdll.LoadLibrary("mk2_rt.dll")
except:
raise ValueError('MKL Library not found')
示例7: make_cuda_ext
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def make_cuda_ext(name, module, sources, sources_cuda=[]):
define_macros = []
extra_compile_args = {'cxx': []}
if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
define_macros += [('WITH_CUDA', None)]
extension = CUDAExtension
extra_compile_args['nvcc'] = [
'-D__CUDA_NO_HALF_OPERATORS__',
'-D__CUDA_NO_HALF_CONVERSIONS__',
'-D__CUDA_NO_HALF2_OPERATORS__',
]
sources += sources_cuda
else:
print(f'Compiling {name} without CUDA')
extension = CppExtension
# raise EnvironmentError('CUDA is required to compile MMDetection!')
return extension(
name=f'{module}.{name}',
sources=[os.path.join(*module.split('.'), p) for p in sources],
define_macros=define_macros,
extra_compile_args=extra_compile_args)
示例8: gpt_device
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def gpt_device(self, dev_name):
disk_dev = self.physical_disk(dev_name)
cmd = ['parted', disk_dev, '-s', 'print']
with open(os.devnull) as devnull:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stdin=devnull)
_cmd_out, _err_out = p.communicate()
p.wait()
if p.returncode != 0:
lang = os.getenv('LANG')
encoding = lang.rsplit('.')[-1] if lang else 'utf-8'
raise RuntimeError(str(_err_out, encoding))
subprocess.check_call(['partprobe', disk_dev])
if b'msdos' in _cmd_out:
return False
if b'gpt' in _cmd_out:
return True
raise RuntimeError("Disk '%s' is uninitialized and not usable." %
disk_dev)
示例9: parse_args
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def parse_args():
args = sys.argv
verbose = '--verbose' in args
only = [e.split('--only=')[1]
for e in args
if e.startswith('--only=')]
checks = all_checks.ALL_CHECKS
if only:
checks = [e for e in checks if e.command_line_switch() in only]
if len(checks) != len(only):
print('Bad --only argument. Allowed values {!r}.'.format(
[e.command_line_switch() for e in all_checks.ALL_CHECKS]),
file=sys.stderr)
sys.exit(1)
checks = topologically_sorted_checks_with_deps(checks)
positionals = [arg for arg in args if not arg.startswith('-')]
pull_request_number = None if len(positionals) < 2 else int(positionals[1])
access_token = None if len(positionals) < 3 else int(positionals[2])
if access_token is None:
access_token = os.getenv('CIRQ_GITHUB_ACCESS_TOKEN')
return pull_request_number, access_token, verbose, checks
示例10: configure
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def configure(dir=None, format_strs=None):
if dir is None:
dir = os.getenv('OPENAI_LOGDIR')
if dir is None:
dir = osp.join(tempfile.gettempdir(),
datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
assert isinstance(dir, str)
os.makedirs(dir, exist_ok=True)
if format_strs is None:
strs = os.getenv('OPENAI_LOG_FORMAT')
format_strs = strs.split(',') if strs else LOG_OUTPUT_FORMATS
output_formats = [make_output_format(f, dir) for f in format_strs]
Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
log('Logging to %s'%dir)
示例11: mpi_fork
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def mpi_fork(n, bind_to_core=False):
"""Re-launches the current script with workers
Returns "parent" for original parent, "child" for MPI children
"""
if n<=1:
return "child"
if os.getenv("IN_MPI") is None:
env = os.environ.copy()
env.update(
MKL_NUM_THREADS="1",
OMP_NUM_THREADS="1",
IN_MPI="1"
)
args = ["mpirun", "-np", str(n)]
if bind_to_core:
args += ["-bind-to", "core"]
args += [sys.executable] + sys.argv
subprocess.check_call(args, env=env)
return "parent"
else:
return "child"
示例12: loadstate
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def loadstate():
global STATE, STATEFILE
if os.getenv("HOME") is not None:
STATEFILE = os.path.join(os.getenv("HOME"), ".epr")
if os.path.isdir(os.path.join(os.getenv("HOME"), ".config")):
configdir = os.path.join(os.getenv("HOME"), ".config", "epr")
os.makedirs(configdir, exist_ok=True)
if os.path.isfile(STATEFILE):
if os.path.isfile(os.path.join(configdir, "config")):
os.remove(os.path.join(configdir, "config"))
shutil.move(STATEFILE, os.path.join(configdir, "config"))
STATEFILE = os.path.join(configdir, "config")
elif os.getenv("USERPROFILE") is not None:
STATEFILE = os.path.join(os.getenv("USERPROFILE"), ".epr")
else:
STATEFILE = os.devnull
if os.path.exists(STATEFILE):
with open(STATEFILE, "r") as f:
STATE = json.load(f)
示例13: publish
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def publish(self, level, msg, ext_info):
sns_arn = os.getenv(ENV_SNS_ISSUE_TOPIC, None)
if sns_arn is not None:
message = {
"log-group": self._loggroup,
"log-stream": self._logstream,
"level": level,
"message": msg
}
if ext_info not in [None, {}]:
for i in ext_info:
message[i.lower()] = ext_info[i]
topic_msg = safe_json({"default": safe_json(message, indent=3), "lambda": message})
resp = self.sns_client.publish_with_retries(TopicArn=sns_arn,
Message=topic_msg,
MessageStructure="json")
print(resp)
示例14: get_action_session
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def get_action_session(self, account, param_name=None, logger=None):
self._logger_.debug("Getting action session for account \"{}\", task is \"{}\", parameter is \"{}\"", account,
self._task_, param_name)
try:
role_name = self.get(param_name, None)
if role_name is None:
role_name = self.get(handlers.TASK_ROLE, None)
if role_name is None:
if account == os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT):
role_name = None
else:
role_name = handlers.default_rolename_for_stack()
role_arn = handlers.ARN_ROLE_TEMPLATE.format(account, role_name) if role_name is not None else None
self._logger_.debug("Role arn is \"{}\"", role_arn)
return services.get_session(role_arn=role_arn, logger=logger)
except Exception as ex:
if logger is not None:
logger.error(handlers.ERR_CREATING_SESSION, ex)
return None
示例15: create_task_config_objects
# 需要导入模块: import os [as 别名]
# 或者: from os import getenv [as 别名]
def create_task_config_objects(self, config_item):
# get the class that implements the action and test if there is a static method for creating templates
action_class = actions.get_action_class(config_item[configuration.CONFIG_ACTION_NAME])
create_task_objects_method = getattr(action_class, "create_task_config_objects", None)
# if the method exists then validate the parameters using the business logic for that class
bucket = os.getenv(configuration.ENV_CONFIG_BUCKET)
prefix = "{}/{}/{}/".format(configuration.TASKS_OBJECTS, config_item[configuration.CONFIG_ACTION_NAME],
config_item[configuration.CONFIG_TASK_NAME])
task_name = config_item[configuration.CONFIG_TASK_NAME]
try:
if create_task_objects_method is not None:
cfg = self.get_parameters(config_item)
objects = create_task_objects_method(cfg)
if objects is not None:
s3 = boto3.client("s3")
for t in objects:
s3.put_object(Bucket=bucket, Key=prefix + t, Body=objects[t])
self._logger.info("Created config object {}/{} in bucket {} for task {}", prefix, t, bucket, task_name)
except Exception as ex:
self._logger.error(ERR_CREATING_TASK_OBJECT, task_name, bucket, prefix, ex)