Debian Codegraph @

docs/source/cookbook/file_or_stdin_stdout.rst

raw
1 .. _Reading/Writing From File or Stdin/Stdout:
2
3 =========================================
4 Reading/Writing From File or Stdin/Stdout
5 =========================================
6 In many CLI applications, it's common to be able to read from a file or stdin, and write to a file or stdout.
7 This allows for the chaining of many CLI applications via pipes ``|``.
8
9 ---------
10 StdioPath
11 ---------
12
13 .. note::
14 :class:`~cyclopts.types.StdioPath` requires **Python 3.12+**.
15 For older Python versions, see :ref:`Alternative Approach (Python < 3.12)` below.
16
17 The recommended approach is to use :class:`~cyclopts.types.StdioPath`, a :class:`~pathlib.Path` subclass that treats ``-`` as stdin (for reading) or stdout (for writing).
18 This follows `common Unix convention <https://clig.dev/#arguments-and-flags>`_ used by many command-line tools.
19
20 .. code-block:: python
21
22 from cyclopts import App
23 from cyclopts.types import StdioPath
24
25 app = App()
26
27 @app.default
28 def scream(input_: StdioPath, output: StdioPath):
29 """Uppercase all input data.
30
31 Parameters
32 ----------
33 input_:
34 Input file path, or "-" for stdin.
35 output:
36 Output file path, or "-" for stdout.
37 """
38 data = input_.read_text()
39 output.write_text(data.upper())
40
41 if __name__ == "__main__":
42 app()
43
44 .. code-block:: console
45
46 $ echo "hello cyclopts users." > demo.txt
47
48 $ python scream.py demo.txt -
49 HELLO CYCLOPTS USERS.
50
51 $ python scream.py demo.txt output.txt && cat output.txt
52 HELLO CYCLOPTS USERS.
53
54 $ echo "foo" | python scream.py - -
55 FOO
56
57 :class:`~cyclopts.types.StdioPath` is pre-configured with ``allow_leading_hyphen=True``, so ``-`` can be passed as an argument without being interpreted as an option.
58
59 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
60 Defaulting to Stdin/Stdout
61 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
62
63 To make stdin/stdout the default when no argument is provided, use ``StdioPath("-")`` as the default value:
64
65 .. code-block:: python
66
67 from cyclopts import App
68 from cyclopts.types import StdioPath
69
70 app = App()
71
72 @app.default
73 def scream(input_: StdioPath = StdioPath("-"), output: StdioPath = StdioPath("-")):
74 """Uppercase all input data.
75
76 Parameters
77 ----------
78 input_:
79 Input file path. Defaults to stdin if not provided.
80 output:
81 Output file path. Defaults to stdout if not provided.
82 """
83 data = input_.read_text()
84 output.write_text(data.upper())
85
86 if __name__ == "__main__":
87 app()
88
89 .. code-block:: console
90
91 $ echo "hello cyclopts users." > demo.txt
92
93 $ python scream.py demo.txt
94 HELLO CYCLOPTS USERS.
95
96 $ python scream.py demo.txt output.txt && cat output.txt
97 HELLO CYCLOPTS USERS.
98
99 $ echo "foo" | python scream.py
100 FOO
101
102 ^^^^^^^^^^^^^
103 Binary Data
104 ^^^^^^^^^^^^^
105
106 ``StdioPath`` also supports binary reading and writing:
107
108 .. code-block:: python
109
110 @app.default
111 def process_binary(input_: StdioPath = StdioPath("-"), output: StdioPath = StdioPath("-")):
112 data = input_.read_bytes()
113 output.write_bytes(data)
114
115 Or using the context manager interface:
116
117 .. code-block:: python
118
119 @app.default
120 def process_binary(input_: StdioPath = StdioPath("-"), output: StdioPath = StdioPath("-")):
121 with input_.open("rb") as f_in, output.open("wb") as f_out:
122 f_out.write(f_in.read())
123
124 .. _Alternative Approach (Python < 3.12):
125
126 -------------------------------------
127 Alternative Approach (Python < 3.12)
128 -------------------------------------
129
130 For Python versions before 3.12, or when you prefer an ``Optional[Path]`` pattern where ``None`` indicates stdin/stdout, you can use helper functions:
131
132 .. code-block:: python
133
134 import sys
135 from cyclopts import App
136 from pathlib import Path
137 from typing import Optional
138
139 def read_str(input_: Optional[Path]) -> str:
140 return sys.stdin.read() if input_ is None else input_.read_text()
141
142 def write_str(output: Optional[Path], data: str):
143 sys.stdout.write(data) if output is None else output.write_text(data)
144
145 def read_bytes(input_: Optional[Path]) -> bytes:
146 return sys.stdin.buffer.read() if input_ is None else input_.read_bytes()
147
148 def write_bytes(output: Optional[Path], data: bytes):
149 sys.stdout.buffer.write(data) if output is None else output.write_bytes(data)
150
151 app = App()
152
153 @app.default
154 def scream(input_: Optional[Path] = None, output_: Optional[Path] = None):
155 """Uppercase all input data.
156
157 Parameters
158 ----------
159 input_ : Optional[Path]
160 If provided, read data from file. If not provided, read from stdin.
161 output_ : Optional[Path]
162 If provided, write data to file. If not provided, write to stdout.
163 """
164 data = read_str(input_)
165 processed = data.upper()
166 write_str(output_, processed)
167
168 if __name__ == "__main__":
169 app()
170
171 .. code-block:: console
172
173 $ echo "hello cyclopts users." > demo.txt
174 $ python scream.py demo.txt
175 HELLO CYCLOPTS USERS.
176 $ python scream.py demo.txt output.txt
177 $ cat output.txt
178 HELLO CYCLOPTS USERS.
179 $ echo "foo" | python scream.py
180 FOO