Skip to content
Myr

Move License and Handling-files doc pages from reST to MyST (#3093)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 61117af, a31eb9b · Browse files · 4 files+109 added−95 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+109 added−95 removed

  • other:+109 added−95 removed

4 files+109 added−95 removed

added:docs/handling-files.md+102 added
1(handling-files)=23# Handling Files45```{currentmodule} click6```78Click has built in features to support file and file path handling. The examples use arguments but the same principle9applies to options as well.1011(file-args)=1213## File Arguments1415Click supports working with files with the {class}`File` type. Some notable features are:1617- Support for `-` to mean a special file that refers to stdin when used for reading, and stdout when used for writing.18 This is a common pattern for POSIX command line utilities.19- Deals with `str` and `bytes` correctly for all versions of Python.2021Example:2223```{eval-rst}24.. click:example::2526 @click.command()27 @click.argument('input', type=click.File('rb'))28 @click.argument('output', type=click.File('wb'))29 def inout(input, output):30 """Copy contents of INPUT to OUTPUT."""31 while True:32 chunk = input.read(1024)33 if not chunk:34 break35 output.write(chunk)3637And from the command line:3839.. click:run::4041 with isolated_filesystem():42 invoke(inout, args=['-', 'hello.txt'], input=['hello'],43 terminate_input=True)44 invoke(inout, args=['hello.txt', '-'])45```4647## File Path Arguments4849For handling paths, the {class}`Path` type is better than a `str`. Some notable features are:5051- The `exists` argument will verify whether the path exists.52- `readable`, `writable`, and `executable` can perform permission checks.53- `file_okay` and `dir_okay` allow specifying whether files/directories are accepted.54- Error messages are nicely formatted using {func}`format_filename` so any undecodable bytes will be printed nicely.5556See {class}`Path` for all features.5758Example:5960```{eval-rst}61.. click:example::6263 @click.command()64 @click.argument('filename', type=click.Path(exists=True))65 def touch(filename):66 """Print FILENAME if the file exists."""67 click.echo(click.format_filename(filename))6869And from the command line:7071.. click:run::7273 with isolated_filesystem():74 with open('hello.txt', 'w') as f:75 f.write('Hello World!\n')76 invoke(touch, args=['hello.txt'])77 println()78 invoke(touch, args=['missing.txt'])79```8081## File Opening Behaviors8283The {class}`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading84will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for85writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special86wrapper.8788File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:8990- A failure at first IO operation will happen by raising an {exc}`FileError`.91- It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call92 {meth}`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for93 parameters, but is necessary for manually prompting. For manual prompts with the {func}`prompt` function you do not94 know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs95 closing).9697Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is98absolutely sure that this is intended behavior.99100It is also possible to open files in atomic mode by passing `atomic=True`. In atomic mode, all writes go into a separate101file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a102file regularly read by other users is modified.
deleted:docs/handling-files.rst-90 removed
1.. _handling-files:23Handling Files4================56.. currentmodule:: click78Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.910.. _file-args:1112File Arguments13-----------------1415Click supports working with files with the :class:`File` type. Some notable features are:1617* Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities.18* Deals with ``str`` and ``bytes`` correctly for all versions of Python.1920Example:2122.. click:example::2324 @click.command()25 @click.argument('input', type=click.File('rb'))26 @click.argument('output', type=click.File('wb'))27 def inout(input, output):28 """Copy contents of INPUT to OUTPUT."""29 while True:30 chunk = input.read(1024)31 if not chunk:32 break33 output.write(chunk)3435And from the command line:3637.. click:run::3839 with isolated_filesystem():40 invoke(inout, args=['-', 'hello.txt'], input=['hello'],41 terminate_input=True)42 invoke(inout, args=['hello.txt', '-'])4344File Path Arguments45----------------------4647For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:4849* The ``exists`` argument will verify whether the path exists.50* ``readable``, ``writable``, and ``executable`` can perform permission checks.51* ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted.52* Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely.5354See :class:`Path` for all features.5556Example:5758.. click:example::5960 @click.command()61 @click.argument('filename', type=click.Path(exists=True))62 def touch(filename):63 """Print FILENAME if the file exists."""64 click.echo(click.format_filename(filename))6566And from the command line:6768.. click:run::6970 with isolated_filesystem():71 with open('hello.txt', 'w') as f:72 f.write('Hello World!\n')73 invoke(touch, args=['hello.txt'])74 println()75 invoke(touch, args=['missing.txt'])767778File Opening Behaviors79-----------------------------8081The :class:`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special wrapper.8283File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:8485* A failure at first IO operation will happen by raising an :exc:`FileError`.86* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).8788Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.8990It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
added:docs/license.md+7 added
deleted:docs/license.rst-5 removed
1BSD-3-Clause License2====================34.. literalinclude:: ../LICENSE.txt5 :language: text