Skip to content

Commit ef96e94

Browse files
committed
add unsetenv()
1 parent 5097f6f commit ef96e94

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

main

8.17 KB
Binary file not shown.

os/os.module.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ func init() {
2020
py.MustNewMethod("getenv", getenv, 0, "Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str."),
2121
py.MustNewMethod("getpid", getpid, 0, "Return the current process id."),
2222
py.MustNewMethod("putenv", putenv, 0, "Set the environment variable named key to the string value."),
23+
py.MustNewMethod("unsetenv", unsetenv, 0, "Unset (delete) the environment variable named key."),
2324
}
2425

2526
globals := py.StringDict{
@@ -136,7 +137,7 @@ func putenv(self py.Object, args py.Tuple) (py.Object, error) {
136137

137138
err = os.Setenv(key, value)
138139
if err != nil {
139-
return nil, py.ExceptionNewf(py.OSError, "Unable to set enviroment variable") // this will never execute
140+
return nil, py.ExceptionNewf(py.OSError, "Unable to set enviroment variable")
140141
}
141142
return py.None, nil
142143
} else {
@@ -146,3 +147,25 @@ func putenv(self py.Object, args py.Tuple) (py.Object, error) {
146147
return nil, py.ExceptionNewf(py.TypeError, "Expected 2 arguments of type string")
147148
}
148149
}
150+
151+
// Unset (delete) the environment variable named key.
152+
func unsetenv(self py.Object, args py.Tuple) (py.Object, error) {
153+
if len(args) == 1 {
154+
if reflect.TypeOf(args[0]).String() == "py.String" {
155+
_k, err := py.ReprAsString(args[0])
156+
if err != nil {
157+
return nil, py.ExceptionNewf(py.TypeError, "Unable to parse string") // this will never execute
158+
}
159+
key := strings.ReplaceAll(_k, "'", "") // required
160+
err = os.Unsetenv(key)
161+
if err != nil {
162+
return nil, py.ExceptionNewf(py.OSError, "Unable to unset enviroment variable")
163+
}
164+
return py.None, nil
165+
} else {
166+
return nil, py.ExceptionNewf(py.TypeError, "Expected 1 argument of type string")
167+
}
168+
} else {
169+
return nil, py.ExceptionNewf(py.TypeError, "Expected 1 argument of type string")
170+
}
171+
}

os/os.test.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,8 @@
1616
print()
1717
print('putenv("TEST_VAR", "TEST_VALUE"):', os.putenv("TEST_VAR", "TEST_VALUE")) # creates a new enviroment variable
1818
print()
19-
print('getenv("TEST_VAR"):', os.getenv("TEST_VAR"))
19+
print('getenv("TEST_VAR"):', os.getenv("TEST_VAR")) # get TEST_VAR value
20+
print()
21+
print('unsetenv("TEST_VAR"):', os.unsetenv("TEST_VAR")) # unset TEST_VAR
22+
print()
23+
print('getenv("TEST_VAR"):',os.getenv("TEST_VAR")) # get TEST_VAR after it has been deleted

0 commit comments

Comments
 (0)