本文整理汇总了Python中os.environ方法的典型用法代码示例。如果您正苦于以下问题:Python os.environ方法的具体用法?Python os.environ怎么用?Python os.environ使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.environ方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_settings
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def get_settings(self):
"""Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
Returns:
dict -- aws-auto-remediate-settings table
"""
settings = {}
try:
for record in boto3.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"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
)
self.logging.error(sys.exc_info()[1])
return settings
示例2: find_executable
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def find_executable(name) -> str:
is_windows = os.name == 'nt'
windows_exts = os.environ['PATHEXT'].split(ENV_PATH_SEP) if is_windows else None
path_dirs = os.environ['PATH'].split(ENV_PATH_SEP)
search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list
for dir in search_dirs:
path = os.path.join(dir, name)
if is_windows:
for extension in windows_exts:
path_with_ext = path + extension
if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
return path_with_ext
else:
if os.path.isfile(path) and os.access(path, os.X_OK):
return path
return ''
示例3: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [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)
# Now we create a forest environment for our agents to act within:
if self.pa["user_type"] == props.WEB:
self.pa["base_dir"] = os.environ["base_dir"]
# Now we create a minimal environment for our agents to act within:
self.env = ge.GridEnv("Test grid env",
self.pa["grid_width"],
self.pa["grid_height"],
torus=False,
model_nm=MODEL_NM,
preact=True,
postact=True,
props=self.pa)
for i in range(self.pa["num_agents"]):
self.env.add_agent(gm.TestGridAgent(name="agent" + str(i),
goal="taking up a grid space!"))
self.env.add_agent(gm.TestGridAgent(name="agent for tracking",
goal="taking up a grid space!"))
示例4: run_migrations_online
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
示例5: put
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def put(args):
if args.generate_ssh_key:
ssh_key = new_ssh_key()
buf = StringIO()
ssh_key.write_private_key(buf)
secret_value = buf.getvalue()
elif args.secret_name in os.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)
except clients.secretsmanager.exceptions.ResourceExistsException:
res = clients.secretsmanager.put_secret_value(SecretId=args.secret_name, SecretString=secret_value)
if parse_principal(args):
ensure_policy(parse_principal(args), res["ARN"])
if args.generate_ssh_key:
return dict(ssh_public_key=hostkey_line(hostnames=[], key=ssh_key).strip(),
ssh_key_fingerprint=key_fingerprint(ssh_key))
示例6: get_VT_name
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def get_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 "") for hash_ in hashes]
if len(names) >= 2 and all(names[0] == name for name in names[1:]):
name = names[0]
if name["pup"]:
log.error("PUA signatures are not implemented yet. Excpected name was: %s", str(name))
pass
else:
return "{}.{}.{}".format(name["platform"], name["category"], name["unique_name"])
except KeyError:
log.warn("No VIRUSTOTAL_API_KEY specified. Falling back to generic name.")
except Exception:
log.exception("White trying to compute VT name. Falling back to generic name.")
return GENERIC_CLAMAV_MALWARE_NAME
示例7: run_ida
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def run_ida(db, is_64_bit, timeout, script, *args):
if os.path.exists(os.path.join(IDA_DIR, "idat")):
# This is IDA >= 7.0
IDA_EXECUTABLE = os.path.join(IDA_DIR, "idat")
else:
IDA_EXECUTABLE = os.path.join(IDA_DIR, "idal")
if is_64_bit:
ida = "{}64".format(IDA_EXECUTABLE)
else:
ida = IDA_EXECUTABLE
cmd = (ida, "-S{} {}".format(script, " ".join("\"{}\"".format(x) for x in args)), "-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("Executing command %s, log output is in '%s'", " ".join("'%s'" % x for x in cmd), env["IDALOG"])
try:
check_call(cmd, timeout = timeout, env = env)
except OSError as err:
if err.errno == -9:
raise TimeoutError(err.errno, "Program execution timed out")
else:
raise err
示例8: index
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def index(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", "") for p in glob(htmls)
]
ctx["PORTAL_CNAME"] = cname
ctx["landing_pages"] = []
mask = ["project", "title", "authors", "is_public", "description", "urls"]
client = Client(headers=get_consumer(request)) # sets/returns global variable
entries = client.projects.get_entries(_fields=mask).result()["data"]
for entry in entries:
authors = entry["authors"].strip().split(",", 1)
if len(authors) > 1:
authors[1] = authors[1].strip()
entry["authors"] = authors
entry["description"] = entry["description"].split(".", 1)[0] + "."
ctx["landing_pages"].append(
entry
) # visibility governed by is_public flag and X-Consumer-Groups header
return render(request, "home.html", ctx.flatten())
示例9: from_environment
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def from_environment(cls, context):
"""
Create a new device from the process environment (as in
:data:`os.environ`).
This only works reliable, if the current process is called from an
udev rule, and is usually used for tools executed from ``IMPORT=``
rules. Use this method to create device objects in Python scripts
called from udev rules.
``context`` is the library :class:`Context`.
Return a :class:`Device` object constructed from the environment.
Raise :exc:`DeviceNotFoundInEnvironmentError`, if no device could be
created from the environment.
.. udevversion:: 152
.. versionadded:: 0.18
"""
device = context._libudev.udev_device_new_from_environment(context)
if not device:
raise DeviceNotFoundInEnvironmentError()
return Device(context, device)
示例10: send_to_missing_remediation_topic
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def send_to_missing_remediation_topic(self, config_rule_name, config_payload):
"""Publishes a message onto the missing remediation SNS Topic. The topic should be subscribed to
by administrators to be aware when their security remediations are not fully covered.
Arguments:
config_rule_name {string} -- AWS Config Rule name
config_payload {dictionary} -- AWS Config Rule payload
"""
client = boto3.client("sns")
topic_arn = os.environ["MISSINGREMEDIATIONTOPIC"]
try:
client.publish(
TopicArn=topic_arn,
Message=json.dumps(config_payload),
Subject=f"No remediation available for Config Rule '{config_rule_name}'",
)
except:
self.logging.error(f"Could not publish to SNS Topic 'topic_arn'.")
示例11: get_settings
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def get_settings(self):
"""Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
Returns:
dict -- aws-auto-remediate-settings table
"""
settings = {}
try:
for record in self.client_dynamodb.scan(
TableName=os.environ["SETTINGSTABLE"]
)["Items"]:
record_json = dynamodb_json.loads(record, True)
if "key" in record_json and "value" in record_json:
settings[record_json.get("key")] = record_json.get("value")
except:
self.logging.error(
f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
)
self.logging.error(sys.exc_info()[1])
return settings
示例12: test_invalid_table_schema
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def test_invalid_table_schema(self, setup):
"""Tests retrieval of settings from DynamoDB with the wrong schema
Arguments:
setup {class} -- Instance of Setup class
"""
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"}}
)
# test get_settings function
assert setup.get_settings() == {}
示例13: _get_full_path
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def _get_full_path(value):
"""
convert string to absolute normpath.
@param value: some string to be converted
@type value: basestring
@return: absolute normpath
@rtype: basestring
"""
assert isinstance(value, basestring)
parent_directory, filename = os.path.split(value)
if not parent_directory and not os.path.isfile(value):
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, filename)
if os.path.isfile(exe_file):
value = exe_file
break
value = os.path.expanduser(value)
value = os.path.normpath(value)
value = os.path.abspath(value)
return value
示例14: update_complete
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def update_complete(self, client):
logger.debug("Self update successful! Edit message")
heroku_key = os.environ.get("heroku_api_token")
herokufail = ("DYNO" in os.environ) and (heroku_key is None)
if herokufail:
logger.warning("heroku token not set")
msg = self.strings["heroku_warning"]
else:
logger.debug("Self update successful! Edit message")
msg = self.strings["success"] if random.randint(0, 10) != 0 else self.strings["success_meme"]
if self.config["AUDIO"]:
await client.send_file(self._db.get(__name__, "selfupdatechat"), STARTUP, caption=msg, voice_note=True)
await client.delete_messages(self._db.get(__name__, "selfupdatechat"),
[self._db.get(__name__, "selfupdatemsg")])
else:
await client.edit_message(self._db.get(__name__, "selfupdatechat"),
self._db.get(__name__, "selfupdatemsg"), msg)
示例15: get_phones
# 需要导入模块: import os [as 别名]
# 或者: from os import environ [as 别名]
def get_phones(arguments):
"""Get phones from the --token, --phone, and environment"""
phones = set(arguments.phone if arguments.phone else [])
phones.update(map(lambda f: f[18:-8],
filter(lambda f: f.startswith("friendly-telegram-") and f.endswith(".session"),
os.listdir(os.path.dirname(utils.get_base_dir())))))
authtoken = os.environ.get("authorization_strings", False) # for heroku
if authtoken and not arguments.setup:
try:
authtoken = json.loads(authtoken)
except json.decoder.JSONDecodeError:
logging.warning("authtoken invalid")
authtoken = False
if arguments.setup or (arguments.tokens and not authtoken):
authtoken = {}
if arguments.tokens:
for token in arguments.tokens:
phone = sorted(phones).pop(0)
phones.remove(phone) # Handled seperately by authtoken logic
authtoken.update(**{phone: token})
return phones, authtoken