unix/moduos: Implement 2-arg version of os.getenv().

This adds the `default` argument of `os.getenv(key, default=None)`.

Signed-off-by: David Lechner <david@pybricks.com>
This commit is contained in:
David Lechner 2022-12-13 12:06:04 -06:00 committed by Damien George
parent 0eba00a92c
commit 958f748e53
2 changed files with 6 additions and 17 deletions

View File

@ -32,14 +32,17 @@
#include "py/runtime.h" #include "py/runtime.h"
#include "py/mphal.h" #include "py/mphal.h"
STATIC mp_obj_t mp_uos_getenv(mp_obj_t var_in) { STATIC mp_obj_t mp_uos_getenv(size_t n_args, const mp_obj_t *args) {
const char *s = getenv(mp_obj_str_get_str(var_in)); const char *s = getenv(mp_obj_str_get_str(args[0]));
if (s == NULL) { if (s == NULL) {
if (n_args == 2) {
return args[1];
}
return mp_const_none; return mp_const_none;
} }
return mp_obj_new_str(s, strlen(s)); return mp_obj_new_str(s, strlen(s));
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_uos_getenv_obj, mp_uos_getenv); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_uos_getenv_obj, 1, 2, mp_uos_getenv);
STATIC mp_obj_t mp_uos_putenv(mp_obj_t key_in, mp_obj_t value_in) { STATIC mp_obj_t mp_uos_putenv(mp_obj_t key_in, mp_obj_t value_in) {
const char *key = mp_obj_str_get_str(key_in); const char *key = mp_obj_str_get_str(key_in);

View File

@ -1,14 +0,0 @@
"""
categories: Modules,os
description: ``getenv`` only allows one argument
cause: Unknown
workaround: Test that the return value is ``None``
"""
import os
try:
print(os.getenv("NEW_VARIABLE", "DEFAULT"))
except TypeError:
print("should not get here")
# this assumes NEW_VARIABLE is never an empty variable
print(os.getenv("NEW_VARIABLE") or "DEFAULT")