diff options
| author | stephanelsmith <stephane.smith@titansensor.com> | 2023-07-26 02:52:56 +0000 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2023-09-01 17:39:38 +1000 |
| commit | db06041d59ef8d5524340c4d2c4490c8e770591f (patch) | |
| tree | b7470931bf9df7f4020708f77867a3a09ab393ef /extmod | |
| parent | 1c047742a273382241e8cfddb12a1d8b4f7f59ab (diff) | |
extmod/vfs_posix_file: Implement sys.std*.buffer objects.
Add the buffer attribute to sys.stdin, sys.stdout and sys.stderr. This
provides raw access to underlying stdio streams for the unix port (and
others that use VfsPosix).
Signed-off-by: stephanelsmith <stephane.smith@titansensor.com>
Diffstat (limited to 'extmod')
| -rw-r--r-- | extmod/vfs_posix_file.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/extmod/vfs_posix_file.c b/extmod/vfs_posix_file.c index cce7a79af..488593230 100644 --- a/extmod/vfs_posix_file.c +++ b/extmod/vfs_posix_file.c @@ -274,12 +274,58 @@ STATIC const mp_stream_p_t vfs_posix_textio_stream_p = { .is_text = true, }; +#if MICROPY_PY_SYS_STDIO_BUFFER + +const mp_obj_vfs_posix_file_t mp_sys_stdin_buffer_obj = {{&mp_type_vfs_posix_fileio}, STDIN_FILENO}; +const mp_obj_vfs_posix_file_t mp_sys_stdout_buffer_obj = {{&mp_type_vfs_posix_fileio}, STDOUT_FILENO}; +const mp_obj_vfs_posix_file_t mp_sys_stderr_buffer_obj = {{&mp_type_vfs_posix_fileio}, STDERR_FILENO}; + +// Forward declarations. +const mp_obj_vfs_posix_file_t mp_sys_stdin_obj; +const mp_obj_vfs_posix_file_t mp_sys_stdout_obj; +const mp_obj_vfs_posix_file_t mp_sys_stderr_obj; + +STATIC void vfs_posix_textio_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + if (dest[0] != MP_OBJ_NULL) { + // These objects are read-only. + return; + } + + if (attr == MP_QSTR_buffer) { + // Implement the `buffer` attribute only on std{in,out,err} instances. + if (MP_OBJ_TO_PTR(self_in) == &mp_sys_stdin_obj) { + dest[0] = MP_OBJ_FROM_PTR(&mp_sys_stdin_buffer_obj); + return; + } + if (MP_OBJ_TO_PTR(self_in) == &mp_sys_stdout_obj) { + dest[0] = MP_OBJ_FROM_PTR(&mp_sys_stdout_buffer_obj); + return; + } + if (MP_OBJ_TO_PTR(self_in) == &mp_sys_stderr_obj) { + dest[0] = MP_OBJ_FROM_PTR(&mp_sys_stderr_buffer_obj); + return; + } + } + + // Any other attribute - forward to locals dict. + dest[1] = MP_OBJ_SENTINEL; +}; + +#define VFS_POSIX_TEXTIO_TYPE_ATTR attr, vfs_posix_textio_attr, + +#else + +#define VFS_POSIX_TEXTIO_TYPE_ATTR + +#endif // MICROPY_PY_SYS_STDIO_BUFFER + MP_DEFINE_CONST_OBJ_TYPE( mp_type_vfs_posix_textio, MP_QSTR_TextIOWrapper, MP_TYPE_FLAG_ITER_IS_STREAM, print, vfs_posix_file_print, protocol, &vfs_posix_textio_stream_p, + VFS_POSIX_TEXTIO_TYPE_ATTR locals_dict, &vfs_posix_rawfile_locals_dict ); |
