Debian Codegraph @

docs/source/app_calling.rst

raw
1 ===========================
2 App Calling & Return Values
3 ===========================
4 In this section, we'll take a closer look at the :meth:`.App.__call__` method.
5
6 -------------
7 Input Command
8 -------------
9 Typically, a Cyclopts app looks something like:
10
11 .. code-block:: python
12
13 from cyclopts import App
14
15 app = App()
16
17 @app.command
18 def foo(a: int, b: int, c: int):
19 print(a + b + c)
20
21 app()
22
23 .. code-block:: console
24
25 $ my-script 1 2 3
26 6
27
28 :meth:`.App.__call__` takes in an optional input that it parses into an action.
29 If not specified, Cyclopts defaults to :data:`sys.argv[1:] <sys.argv>`, i.e. the list of command line arguments.
30 An explicit string or list of strings can instead be passed in.
31
32 .. code-block:: python
33
34 app("foo 1 2 3")
35 # 6
36 app(["foo", "1", "2", "3"])
37 # 6
38
39 If a string is passed in, it will be internally converted into a list using `shlex.split <https://docs.python.org/3/library/shlex.html#shlex.split>`_.
40
41 ------------
42 Return Value
43 ------------
44 The ``app`` invocation processes the command's return value based on :attr:`.App.result_action`. By default, Cyclopts calls :func:`sys.exit` with an appropriate exit code:
45
46 .. code-block:: python
47
48 from cyclopts import App
49
50 app = App() # Default result_action="print_non_int_sys_exit"
51
52 @app.command
53 def success():
54 return 0 # Exit code for success
55
56 @app.command
57 def greet(name: str) -> str:
58 return f"Hello {name}!" # Prints and exits with 0
59
60 if __name__ == "__main__":
61 app() # Will call sys.exit with the returned 0 error code (success).
62
63 `Installed scripts <https://packaging.python.org/en/latest/specifications/entry-points/#use-for-scripts>`_ call :func:`sys.exit` with the returned value of the entry point. So the default Cyclopts :attr:`.App.result_action` will have consistent behavior for standalone scripts and installed apps.
64
65 For embedding Cyclopts in other Python code or testing, use ``result_action="return_value"`` to get the raw command return value without calling :func:`sys.exit`:
66
67 .. code-block:: python
68
69 from cyclopts import App
70
71 app = App(result_action="return_value")
72
73 @app.command
74 def foo(a: int, b: int, c: int):
75 return a + b + c
76
77 return_value = app("foo 1 2 3") # no longer exits!
78 print(f"The return value was: {return_value}.")
79 # The return value was: 6.
80
81 See :ref:`Result Action` for all available modes and detailed behavior.
82
83
84 ------------------------------
85 Exception Handling and Exiting
86 ------------------------------
87 For the most part, Cyclopts is **hands-off** when it comes to handling exceptions and exiting the application.
88 However, by default, if there is a **Cyclopts runtime error**, like :exc:`.CoercionError` or a :exc:`.ValidationError`, then Cyclopts will perform a :func:`sys.exit(1) <sys.exit>`.
89 This is to avoid displaying the unformatted, uncaught exception to the CLI user.
90
91 These behaviors can be controlled via :class:`.App` attributes or method parameters:
92
93 - :attr:`.App.exit_on_error` - Calls :func:`sys.exit(1) <sys.exit>` on errors (defaults to :obj:`True`)
94 - :attr:`.App.print_error` - Formatted errors are printed (defaults to :obj:`True`)
95 - :attr:`.App.help_on_error` - The help-page is printed before errors (defaults to :obj:`False`)
96 - :attr:`.App.verbose` - Include verbose error information that might be useful for **developers** using Cyclopts (defaults to :obj:`False`)
97 - :attr:`.App.error_formatter` - Customize how error messages are formatted (defaults to :func:`.CycloptsPanel`)
98
99 These attributes are inherited by child apps and can be overridden by providing parameters to method calls.
100
101 .. note::
102 Cyclopts separates normal output from error messages using two different consoles:
103
104 - :attr:`.App.console` - Used for normal output like help messages and version information (defaults to stdout)
105 - :attr:`.App.error_console` - Used for error messages like parsing errors and exceptions (defaults to stderr)
106
107
108 **Setting at App Level:**
109
110 .. code-block:: python
111
112 # Configure error handling at the app level
113 app = App(
114 exit_on_error=False, # Don't exit on errors
115 print_error=False, # Don't print formatted errors
116 )
117
118 # Child apps inherit these settings
119 child_app = App(name="child")
120 app.command(child_app)
121
122 **Method-Level Override:**
123
124 .. code-block:: python
125
126 app("this-is-not-a-registered-command")
127 print("this will not be printed since cyclopts exited above.")
128 # ╭─ Error ─────────────────────────────────────────────────────────────╮
129 # │ Unknown command "this-is-not-a-registered-command". │
130 # ╰─────────────────────────────────────────────────────────────────────╯
131
132 app("this-is-not-a-registered-command", exit_on_error=False, print_error=False)
133 # Traceback (most recent call last):
134 # File "/cyclopts/scratch.py", line 9, in <module>
135 # app("this-is-not-a-registered-command", exit_on_error=False, print_error=False)
136 # File "/cyclopts/cyclopts/core.py", line 1102, in __call__
137 # command, bound, _ = self.parse_args(
138 # File "/cyclopts/cyclopts/core.py", line 1037, in parse_args
139 # command, bound, unused_tokens, ignored, argument_collection = self._parse_known_args(
140 # File "/cyclopts/cyclopts/core.py", line 966, in _parse_known_args
141 # raise UnknownCommandError(unused_tokens=unused_tokens)
142 # cyclopts.exceptions.UnknownCommandError: Unknown command "this-is-not-a-registered-command".
143
144 try:
145 app("this-is-not-a-registered-command", exit_on_error=False, print_error=False)
146 except CycloptsError:
147 pass
148 print("Execution continues since we caught the exception.")
149
150 With ``exit_on_error=False``, the ``UnknownCommandError`` is raised the same as a normal python exception.
151
152 .. _Custom Error Formatting:
153
154 -----------------------
155 Custom Error Formatting
156 -----------------------
157 By default, Cyclopts displays errors using :func:`.CycloptsPanel`, which renders a Rich panel:
158
159 .. code-block:: text
160
161 ╭─ Error ───────────────────────────────────────────────╮
162 │ Invalid value for VALUE: unable to convert "foo" │
163 │ into int. │
164 ╰───────────────────────────────────────────────────────╯
165
166 To customize this, set :attr:`.App.error_formatter` to a callable that receives a :exc:`.CycloptsError` and returns any Rich-printable object.
167
168 .. code-block:: python
169
170 from cyclopts import App, CycloptsError
171
172 def my_error_formatter(e: CycloptsError):
173 return f"[bold red]error[/bold red]: {e}"
174
175 app = App(error_formatter=my_error_formatter)
176
177 @app.default
178 def main(value: int):
179 pass
180
181 .. code-block:: text
182
183 $ my-app foo
184 error: Invalid value for VALUE: unable to convert "foo" into int.
185
186 The formatter receives the full :exc:`.CycloptsError` exception, which contains context like the :attr:`~.CycloptsError.command_chain`, :attr:`~.CycloptsError.argument`, and :attr:`~.CycloptsError.target`.
187 Use ``str(e)`` for just the message text.
188
189 Like other error-handling attributes, ``error_formatter`` can also be passed as a runtime override:
190
191 .. code-block:: python
192
193 app.parse_args("foo", error_formatter=my_error_formatter)