Browse Source

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>
pull/8955/head
David Lechner 2 years ago
committed by Damien George
parent
commit
958f748e53
  1. 9
      ports/unix/moduos.c
  2. 14
      tests/cpydiff/modules_os_getenv_argcount.py

9
ports/unix/moduos.c

@ -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);

14
tests/cpydiff/modules_os_getenv_argcount.py

@ -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")
Loading…
Cancel
Save