|
9 | 9 | "os" |
10 | 10 | "os/exec" |
11 | 11 | "runtime" |
| 12 | + "strconv" |
12 | 13 | "strings" |
13 | 14 |
|
14 | 15 | "github.com/go-python/gpython/py" |
@@ -45,6 +46,7 @@ func init() { |
45 | 46 |
|
46 | 47 | methods := []*py.Method{ |
47 | 48 | py.MustNewMethod("_exit", _exit, 0, "Immediate program termination."), |
| 49 | + py.MustNewMethod("fdopen", fdopen, 0, fdopen_doc), |
48 | 50 | py.MustNewMethod("getcwd", getCwd, 0, "Get the current working directory"), |
49 | 51 | py.MustNewMethod("getcwdb", getCwdb, 0, "Get the current working directory in a byte slice"), |
50 | 52 | py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"), |
@@ -96,6 +98,53 @@ func getEnvVariables() py.StringDict { |
96 | 98 | return dict |
97 | 99 | } |
98 | 100 |
|
| 101 | +const fdopen_doc = `# Supply os.fdopen()` |
| 102 | + |
| 103 | +func fdopen(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) { |
| 104 | + var ( |
| 105 | + pyfd py.Object |
| 106 | + pymode py.Object = py.String("r") |
| 107 | + pybuffering py.Object = py.Int(-1) |
| 108 | + pyencoding py.Object = py.None |
| 109 | + ) |
| 110 | + err := py.ParseTupleAndKeywords( |
| 111 | + args, kwargs, |
| 112 | + "i|s#is#", []string{"fd", "mode", "buffering", "encoding"}, |
| 113 | + &pyfd, &pymode, &pybuffering, &pyencoding, |
| 114 | + ) |
| 115 | + if err != nil { |
| 116 | + return nil, err |
| 117 | + } |
| 118 | + |
| 119 | + // FIXME(sbinet): handle buffering |
| 120 | + // FIXME(sbinet): handle encoding |
| 121 | + |
| 122 | + var ( |
| 123 | + fd = uintptr(pyfd.(py.Int)) |
| 124 | + name = strconv.Itoa(int(fd)) |
| 125 | + mode string |
| 126 | + ) |
| 127 | + |
| 128 | + switch v := pymode.(type) { |
| 129 | + case py.String: |
| 130 | + mode = string(v) |
| 131 | + case py.Bytes: |
| 132 | + mode = string(v) |
| 133 | + } |
| 134 | + |
| 135 | + perm, _, _, err := py.FileModeFrom(mode) |
| 136 | + if err != nil { |
| 137 | + return nil, err |
| 138 | + } |
| 139 | + |
| 140 | + f := os.NewFile(fd, name) |
| 141 | + if f == nil { |
| 142 | + return nil, py.ExceptionNewf(py.OSError, "Bad file descriptor") |
| 143 | + } |
| 144 | + |
| 145 | + return &py.File{f, perm}, nil |
| 146 | +} |
| 147 | + |
99 | 148 | // getCwd returns the current working directory. |
100 | 149 | func getCwd(self py.Object, args py.Tuple) (py.Object, error) { |
101 | 150 | dir, err := os.Getwd() |
|
0 commit comments