faqs.md
This file
Path
docs/faqs.md
251 lines · 10.9 KiB · Markdown
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
History of this fileTake it
The walk stopped after 200 commits: lines older than 9ce34f2 point at it.
Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 1–9why, one step back1# Frequently Asked Questions23```{contents}4:depth: 25:local: true6```78## General9Stable (#3851)Rowlando13before adoption6aabf09
lines 10–52why, one step back10### Calling a command as a regular function1112I decorated a function with `@click.command()` to make it a CLI. When I import that name and call it from Python, it does not run my function. It parses arguments, prints a usage error and exits the process:1314```pytb15>>> nasa_date_to_iso("2017-090")16Usage: cli [OPTIONS] DATESTR17Try 'cli --help' for help.1819Error: Got unexpected extra arguments (0 1 7 - 0 9 0)20SystemExit: 221```2223#### Answer2425This is not a bug in Click. The decorator replaced the function with a {class}`Command` object. Calling that object runs the Click pipeline, and its argument is the list of command line arguments to parse, not the function's parameters.2627The recommended pattern is to keep a plain function and wrap it with a thin command:2829```python30def nasa_date_to_iso(datestr): ...313233@click.command("nasa_date_to_iso")34@click.argument("datestr")35def nasa_date_to_iso_command(datestr):36 click.echo(nasa_date_to_iso(datestr))37```3839The function stays available as a Python API, and the command adds the CLI on top. Extracting behavior into a shared function used by several entry points is a common refactor.4041If you still want to run the command itself from Python, call it with a list of arguments and `standalone_mode=False` so it returns the result instead of exiting. This runs the Click pipeline, including parsing, validation and callbacks:4243```python44nasa_date_to_iso_command(["2017-090"], standalone_mode=False)45```4647An alternative form is:4849```python50nasa_date_to_iso_command.main(["2017-090"], standalone_mode=False)51```52Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 53–82why, one step back53### Shell Variable Expansion On Windows5455I have a simple Click app :5657```58import click5960@click.command()61@click.argument('message')62def main(message: str):63 click.echo(message)6465if __name__ == '__main__':66 main()6768```6970When you pass an environment variable in the argument, it expands it:7172```{code-block} powershell73> Desktop python foo.py '$M0/.viola/2025-01-25-17-20-23-307878'74> M:/home/ramrachum/.viola/2025-01-25-17-20-23-30787875>76```77Note that I used single quotes above, so my shell is not expanding the environment variable, Click does. How do I get Click to not expand it?7879#### Answer8081If you don't want Click to emulate (as best it can) unix expansion on Windows, pass windows_expand_args=False when calling the CLI.82Windows command line doesn't do any *, ~, or $ENV expansion. It also doesn't distinguish between double quotes and single quotes (where the later means "don't expand here"). Click emulates the expansion so that the app behaves similarly on both platforms, but doesn't receive information about what quotes were used.Add FAQ entry about `UnicodeEncodeError` on Windows (#3778)Rowlando13before adoption2c8cd3a
lines 83–127why, one step back8384### `UnicodeEncodeError` on Windows8586A Click CLI that uses Unicode characters in its help text or `echo` output can raise `UnicodeEncodeError`:8788```pytb89UnicodeEncodeError: 'charmap' codec can't encode character '\u2023' in position 62: character maps to <undefined>90```9192This is not a bug in Click. When `<stdout>` is a console, Click relies on the Windows console API, which supports full Unicode rendering. But when `<stdout>` is redirected, it cannot use that API, so Python falls back to encoding the stream with the system's code page (often `cp1252`) and `errors="strict"`. That codec cannot represent every Unicode character, so the write fails.9394#### Answer9596Run Python in [UTF-8 mode](https://docs.python.org/3/library/os.html#utf8-mode) so that redirected streams use UTF-8 instead of the code page.9798You can enforce that by:99- Setting the `PYTHONUTF8=1` environment variable, or100- Passing `-X utf8` to the `python` executable, or101- Setting `PYTHONIOENCODING=utf8`, which configures only the standard streams, or102- From your code, call `sys.stdout.reconfigure(encoding="utf-8")` and `sys.stderr.reconfigure(encoding="utf-8")` before producing output.103104This is not a bug for Click to fix, but a system configuration. It will naturally go away with UTF-8 mode becoming the default in Python 3.15 (see [PEP 686](https://peps.python.org/pep-0686/)).105106#### For library authors107108Click intentionally does not fix this in code: it has no way to know what the caller expects. Reconfiguring the stream itself would mix encodings within one process: `echo` could write UTF-8 to a redirected file while a bare `print()` still writes the code page. A loud `UnicodeEncodeError` is easier to diagnose than silently interleaved encodings.109110But if your own CLI knows the environment it runs under, it can choose to degrade its output:111112```python113import sys114115encoding = getattr(sys.stdout, "encoding", "") or ""116ascii_only = not encoding.lower().startswith("utf")117```118119Note that the check we recommend here is against `sys.stdout.encoding`, not `sys.flags.utf8_mode`: only the former reports UTF-8 for all three options listed below.120121| Invocation | `sys.flags.utf8_mode` | `sys.stdout.encoding` |122| :-------------------------------------- | :-------------------: | :-------------------: |123| `PYTHONIOENCODING=utf8` | `0` | `utf-8` |124| `python -X utf8` | `1` | `utf-8` |125| `sys.stdout.reconfigure(encoding=…)` | `0` | `utf-8` |126127Do not rely on `sys.getfilesystemencoding()` on Windows either: [PEP 529](https://peps.python.org/pep-0529/) makes it `utf-8` regardless of the actual stream encoding.Stable (#3851)Rowlando13before adoption6aabf09
lines 128–251why, one step back128129(edit-wait)=130### The `edit` utility fails to open Visual Studio Code131132Let's say our default editor is Visual Studio Code. A Click CLI calling `edit()` is supposed to open a new VSCode window on a temporary file then wait for us to edit that file before returning back the CLI execution.133134But VSCode (and some other editors) returns immediately: the file is deleted before you had a chance to edit it. With `require_save=True` (the default), the function also returns `None` instead of the edited content.135136This is not a bug in Click. In that particular case, the `code` command (VSCode's executable) is a launcher: it starts the real editor in the background, then exits. Click waits on that process and reads its exit as the end of the editing session. The same happens on any platform with any editor whose command returns before its window closes.137138#### Answer139140Setup your editor to make its launcher block until the window is closed, so Click keeps waiting on it.141142You can set the `EDITOR` in your environment with its appropriate flags:143144| Editor | Flags |145|---|---|146| Visual Studio Code | `EDITOR="code --wait"` |147| Sublime Text | `EDITOR="subl -w"` |148149For an editor with no such flag, a workaround is to point `EDITOR` at a small wrapper script that opens the editor and blocks until it exits.150151### Tab completion during interactive prompts152153A command asks for a file path while it runs:154155```python156import click157158159@click.command()160def convert():161 source = click.prompt("File to convert", type=click.Path(exists=True))162 click.echo(f"Converting {source}")163```164165Pressing {kbd}`Tab` while typing the answer inserts a tab character instead of completing the path:166167```console168$ convert169File to convert: Doc<TAB>170Error: Path 'Doc\t' does not exist.171```172173This is not a bug in Click. Tab completion of the command line belongs to the shell: the shell asks the program for candidates through Click's completion mode, before any command code runs. A prompt works the other way around. The program already runs and reads the line itself, so Click never sees the {kbd}`Tab` key.174175{func}`~click.prompt` reads that line with the built-in {func}`input`, and Click passes the whole prompt text to it as-is. This is where Python's {mod}`readline` module takes over, but nothing binds {kbd}`Tab` to completion by default.176177#### Answer178179Bind {kbd}`Tab` in `readline` and the prompt completes paths with no other change:180181```python182import readline183184if "libedit" in (readline.__doc__ or ""):185 readline.parse_and_bind("bind ^I rl_complete")186else:187 readline.parse_and_bind("tab: complete")188```189190See the {mod}`readline` documentation for the binding syntax, for the two libraries it can be built on, and for writing a completer of your own. The module is Unix-only, so the import fails on Windows.191192Readline completes file names. It knows nothing about the parameter, so it cannot complete other values, such as the choices of a {class}`~click.Choice` parameter. Click embeds no line editor of its own: for completion of such values at a prompt, use one of the [interactive input libraries](contrib.md#interactive-input-libraries).193194When the value does not have to be asked while the command runs, another option is to take it out of the prompt and put it on the command line, as an argument or an option:195196```python197@click.command()198@click.argument("source", type=click.Path(exists=True))199def convert(source):200 click.echo(f"Converting {source}")201```202203The shell completes paths there natively and Click's completion mode takes part in it (as described in [Shell Completion](shell-completion.md)).204205(custom-completions-show-the-full-value)=206### Custom completions show the full value207208`Path` and `File` parameters complete differently from a parameter with a custom completer. Take a command with one of each:209210```python211def complete_dirs(ctx, param, incomplete):212 return [213 CompletionItem(incomplete + name)214 for name in ("Documents", "Downloads", "Pictures")215 ]216217218@click.command()219@click.option("--src", type=click.Path())220@click.option("--dest", shell_complete=complete_dirs)221def copy(src, dest):222 click.echo(f"Copy from {src} to {dest}")223```224225Completing `--src` shows only the last component of each candidate, and omits the leading path:226227```console228$ copy --src /home/user/<TAB><TAB>229Documents Downloads Pictures230```231232Completing `--dest` shows each value in full, exactly as the completer returned it:233234```console235$ copy --dest /home/user/<TAB><TAB>236/home/user/Documents /home/user/Downloads /home/user/Pictures237```238239This is not a bug in Click. The two parameters are completed by different sides.240241`Path.shell_complete` and `File.shell_complete` never enumerate the directory: each returns a single item that is the incomplete value itself, tagged `file` (or `dir` for a `Path` restricted to directories). Then the shell takes over to propose completions, and each shell does so in its own way.242243A custom completer sends no such marker. Its `CompletionItem` carries the value, a `type` marker, and an optional `help` string. The value a completer returns is both what the shell displays and what it inserts into the command line.244245#### Answer246247To change how suggestions are displayed, work on the shell side:248249- Check whether your shell's completion system has an option that changes how candidates are displayed.250- Write a `ShellComplete` subclass and register it with `add_completion_class`, as described in [Adding Support for a Shell](shell-completion.md#adding-support-for-a-shell).251- Or return the shortened form directly from your completer, but make the parameter accept and interpret that shortened form into the full value.