@@ -6,6 +6,7 @@ package os
6
6
7
7
import (
8
8
"os"
9
+ "reflect"
9
10
"strings"
10
11
11
12
"github.com/go-python/gpython/py"
@@ -15,6 +16,7 @@ func init() {
15
16
16
17
methods := []* py.Method {
17
18
py .MustNewMethod ("getcwd" , getCwd , 0 , "Get the current working directory" ),
19
+ py .MustNewMethod ("chdir" , chdir , 0 , "Change the current working directory" ),
18
20
}
19
21
20
22
globals := py.StringDict {
@@ -52,3 +54,25 @@ func getCwd(self py.Object, args py.Tuple) (py.Object, error) {
52
54
}
53
55
return py .String (dir ), nil
54
56
}
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
+ }
0 commit comments