Skip to content

Commit 94e9974

Browse files
committed
added getenv()
1 parent cf840ed commit 94e9974

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed

main

4.05 KB
Binary file not shown.

os/os.module.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ func init() {
1717
methods := []*py.Method{
1818
py.MustNewMethod("getcwd", getCwd, 0, "Get the current working directory"),
1919
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
20+
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."),
2021
}
2122

2223
globals := py.StringDict{
@@ -76,3 +77,37 @@ func chdir(self py.Object, args py.Tuple) (py.Object, error) {
7677
}
7778
}
7879
}
80+
81+
// get a enviroment variable by key
82+
// Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str.
83+
func getenv(self py.Object, args py.Tuple) (py.Object, error) {
84+
var key py.Object // key to search for
85+
var default_ py.Object // return when not found
86+
var err error // error obj
87+
88+
if len(args) > 2 {
89+
return nil, py.ExceptionNewf(py.KeyError, "1 argument required, \"key\"")
90+
} else {
91+
if len(args) == 1 {
92+
if reflect.TypeOf(args[0]).String() == "py.String" {
93+
key = args[0]
94+
} else {
95+
return nil, py.ExceptionNewf(py.TypeError, "Expected argument of type string")
96+
}
97+
default_ = py.None
98+
} else if len(args) == 2 {
99+
if reflect.TypeOf(args[0]).String() == "py.String" && reflect.TypeOf(args[1]).String() == "py.String" {
100+
key = args[0]
101+
default_ = args[1]
102+
} else {
103+
return nil, py.ExceptionNewf(py.TypeError, "Expected argument of type string")
104+
}
105+
}
106+
var res py.Object // hold the result value
107+
res, err = getEnvVariables().M__getitem__(key)
108+
if err != nil {
109+
return default_, nil
110+
}
111+
return res, nil
112+
}
113+
}

os/os.test.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import os
22

3-
print("OS Error ", os.error)
4-
print("$HOME", os.environ.get("HOME")) # prints $HOME variable
3+
print("os.error: ", os.error)
4+
print()
5+
print("$HOME: ", os.environ.get("HOME")) # prints $HOME variable
6+
print()
57
print("cwd():", os.getcwd())
8+
print()
69
print("chdir():", os.chdir(os.environ.get("HOME")))
10+
print()
711
print("cwd() after chdir():", os.getcwd())
12+
print()
13+
print("getenv(\"HOME\"):", os.getenv("HOME"))

0 commit comments

Comments
 (0)