Skip to content

Commit cf840ed

Browse files
committed
add chdir()
1 parent 6d3615b commit cf840ed

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

main

8.25 KB
Binary file not shown.

os/os.module.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package os
66

77
import (
88
"os"
9+
"reflect"
910
"strings"
1011

1112
"github.com/go-python/gpython/py"
@@ -15,6 +16,7 @@ func init() {
1516

1617
methods := []*py.Method{
1718
py.MustNewMethod("getcwd", getCwd, 0, "Get the current working directory"),
19+
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
1820
}
1921

2022
globals := py.StringDict{
@@ -52,3 +54,25 @@ func getCwd(self py.Object, args py.Tuple) (py.Object, error) {
5254
}
5355
return py.String(dir), nil
5456
}
57+
58+
// change current working directory
59+
func chdir(self py.Object, args py.Tuple) (py.Object, error) {
60+
if len(args) == 0 || len(args) > 1 {
61+
return nil, py.ExceptionNewf(py.TypeError, "One argument required")
62+
} else {
63+
if reflect.TypeOf(args[0]).String() == "py.String" {
64+
dir, err := py.ReprAsString(args[0])
65+
if err != nil {
66+
return nil, py.ExceptionNewf(py.TypeError, "Failed to parse string")
67+
}
68+
dir = strings.ReplaceAll(dir, "'", "")
69+
err = os.Chdir(dir)
70+
if err != nil {
71+
return nil, py.ExceptionNewf(py.OSError, "Couldn't change cwd; "+err.Error())
72+
}
73+
return py.None, nil
74+
} else {
75+
return nil, py.ExceptionNewf(py.TypeError, "Expected string argument at position 0")
76+
}
77+
}
78+
}

os/os.test.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22

33
print("OS Error ", os.error)
44
print("$HOME", os.environ.get("HOME")) # prints $HOME variable
5-
print("cwd():", os.getcwd())
5+
print("cwd():", os.getcwd())
6+
print("chdir():", os.chdir(os.environ.get("HOME")))
7+
print("cwd() after chdir():", os.getcwd())

0 commit comments

Comments
 (0)