Skip to content

Add os.listdir #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
57 changes: 57 additions & 0 deletions stdlib/os/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func init() {
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
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."),
py.MustNewMethod("getpid", getpid, 0, "Return the current process id."),
py.MustNewMethod("listdir", listDir, 0, listDir_doc),
py.MustNewMethod("makedirs", makedirs, 0, makedirs_doc),
py.MustNewMethod("mkdir", mkdir, 0, mkdir_doc),
py.MustNewMethod("putenv", putenv, 0, "Set the environment variable named key to the string value."),
Expand Down Expand Up @@ -234,6 +235,62 @@ func getpid(self py.Object, args py.Tuple) (py.Object, error) {
return py.Int(os.Getpid()), nil
}

const listDir_doc = `
Return a list containing the names of the files in the directory.

path can be specified as either str, bytes. If path is bytes, the filenames
returned will also be bytes; in all other circumstances
the filenames returned will be str.
If path is None, uses the path='.'.

The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
`

func listDir(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
var (
path py.Object = py.None
)
err := py.ParseTupleAndKeywords(args, kwargs, "|z*:listdir", []string{"path"}, &path)
if err != nil {
return nil, err
}

if path == py.None {
cwd, err := os.Getwd()
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "cannot get cwd, error %s", err.Error())
}
path = py.String(cwd)
}

dirName := ""
returnsBytes := false
switch v := path.(type) {
case py.String:
dirName = string(v)
case py.Bytes:
dirName = string(v)
returnsBytes = true
default:
return nil, py.ExceptionNewf(py.TypeError, "str or bytes expected, not %T", path)
}

dirEntries, err := os.ReadDir(dirName)
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "cannot read directory %s, error %s", dirName, err.Error())
}
result := py.NewListSized(len(dirEntries))
for i, dirEntry := range dirEntries {
if returnsBytes {
result.Items[i] = py.Bytes(dirEntry.Name())
} else {
result.Items[i] = py.String(dirEntry.Name())
}
}
return result, nil
}

const makedirs_doc = `makedirs(name [, mode=0o777][, exist_ok=False])

Super-mkdir; create a leaf directory and all intermediate ones. Works like
Expand Down
6 changes: 6 additions & 0 deletions stdlib/os/testdata/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@
os.mkdir(dir1)
os.mkdir(dir2)
os.mkdir(dir11)
print(os.listdir(bytes(top, "utf-8")))
orig = os.getcwd()
os.chdir(top)
print(os.listdir())
os.chdir(orig)
os.removedirs(dir1)
try:
os.mkdir(dir11)
Expand Down Expand Up @@ -181,6 +186,7 @@
print("INVALID error caught: %s" % e)
os.remove(fname)
os.rmdir(dir2)
print(os.listdir(top))
except Exception as e:
print("could not create/remove directories: %s" % e)
finally:
Expand Down
3 changes: 3 additions & 0 deletions stdlib/os/testdata/test_golden.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ os.linesep: [OK]
os.devnull: [OK]
os.altsep: [OK]
caught: OSError: 'Bad file descriptor' [OK]
[b'dir1', b'dir2']
['dir1', 'dir2']
caught: SystemError - no such file or directory [OK]
caught: FileExistsError [OK]
caught: SystemError - directory not empty [OK]
['dir1']
os.{mkdir,rmdir,remove,removedirs} worked as expected
OK