Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
stdlib/os: implement fdopen
Signed-off-by: Sebastien Binet <binet@cern.ch>
  • Loading branch information
sbinet committed May 25, 2022
commit fda1751ef78e0b3a20ffff55bb670720ce6d4989
49 changes: 49 additions & 0 deletions stdlib/os/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"os/exec"
"runtime"
"strconv"
"strings"

"github.com/go-python/gpython/py"
Expand Down Expand Up @@ -45,6 +46,7 @@ func init() {

methods := []*py.Method{
py.MustNewMethod("_exit", _exit, 0, "Immediate program termination."),
py.MustNewMethod("fdopen", fdopen, 0, fdopen_doc),
py.MustNewMethod("getcwd", getCwd, 0, "Get the current working directory"),
py.MustNewMethod("getcwdb", getCwdb, 0, "Get the current working directory in a byte slice"),
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
Expand Down Expand Up @@ -96,6 +98,53 @@ func getEnvVariables() py.StringDict {
return dict
}

const fdopen_doc = `# Supply os.fdopen()`

func fdopen(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
var (
pyfd py.Object
pymode py.Object = py.String("r")
pybuffering py.Object = py.Int(-1)
pyencoding py.Object = py.None
)
err := py.ParseTupleAndKeywords(
args, kwargs,
"i|s#is#", []string{"fd", "mode", "buffering", "encoding"},
&pyfd, &pymode, &pybuffering, &pyencoding,
)
if err != nil {
return nil, err
}

// FIXME(sbinet): handle buffering
// FIXME(sbinet): handle encoding

var (
fd = uintptr(pyfd.(py.Int))
name = strconv.Itoa(int(fd))
mode string
)

switch v := pymode.(type) {
case py.String:
mode = string(v)
case py.Bytes:
mode = string(v)
}

perm, _, _, err := py.FileModeFrom(mode)
if err != nil {
return nil, err
}

f := os.NewFile(fd, name)
if f == nil {
return nil, py.ExceptionNewf(py.OSError, "Bad file descriptor")
}

return &py.File{f, perm}, nil
}

// getCwd returns the current working directory.
func getCwd(self py.Object, args py.Tuple) (py.Object, error) {
dir, err := os.Getwd()
Expand Down
9 changes: 9 additions & 0 deletions stdlib/os/testdata/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@
else:
print("os."+k+": [OK]")

## fdopen
import tempfile
fd, tmp = tempfile.mkstemp()
f = os.fdopen(fd, "w+")
## if f.name != str(fd):
## print("invalid fd-name:", f.name)
f.close()
os.remove(tmp)

## mkdir,rmdir,remove,removedirs
import tempfile
try:
Expand Down