Cleanup handling files documentation.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by unknown · committed by unknown · parent e26d89d · Browse files · 4 files·+97 added−115 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+97 added−115 removed
- other:+97 added−115 removed
Provenance
- Commit
50bfe23- Tree
bf3c0be- Author
unknown <edward.g2013@gmail.com>- Committer
unknown <edward.g2013@gmail.com>- Parent
e26d89d
4 files changed+97 added−115 removed
deleted:docs/handling_files.rst-110 removed
1-.. _handling-files:2-3-Handling Files4-================5-6-.. currentmodule:: click7-8-File and files paths are often passed in as arguments.9-10-.. _file-args:11-12-File Arguments13---------------14-15-Since all the examples have already worked with filenames, it makes sense16-to explain how to deal with files properly. Command line tools are more17-fun if they work with files the Unix way, which is to accept ``-`` as a18-special file that refers to stdin/stdout.19-20-Click supports this through the :class:`click.File` type which21-intelligently handles files for you. It also deals with Unicode and bytes22-correctly for all versions of Python so your script stays very portable.23-24-Example:25-26-.. click:example::27-28- @click.command()29- @click.argument('input', type=click.File('rb'))30- @click.argument('output', type=click.File('wb'))31- def inout(input, output):32- """Copy contents of INPUT to OUTPUT."""33- while True:34- chunk = input.read(1024)35- if not chunk:36- break37- output.write(chunk)38-39-And what it does:40-41-.. click:run::42-43- with isolated_filesystem():44- invoke(inout, args=['-', 'hello.txt'], input=['hello'],45- terminate_input=True)46- invoke(inout, args=['hello.txt', '-'])47-48-File Path Arguments49--------------------50-51-In the previous example, the files were opened immediately. But what if52-we just want the filename? The naïve way is to use the default string53-argument type. The :class:`Path` type has several checks available which raise nice54-errors if they fail, such as existence. Filenames in these error messages are formatted55-with :func:`format_filename`, so any undecodable bytes will be printed nicely.56-57-Example:58-59-.. click:example::60-61- @click.command()62- @click.argument('filename', type=click.Path(exists=True))63- def touch(filename):64- """Print FILENAME if the file exists."""65- click.echo(click.format_filename(filename))66-67-And what it does:68-69-.. click:run::70-71- with isolated_filesystem():72- with open('hello.txt', 'w') as f:73- f.write('Hello World!\n')74- invoke(touch, args=['hello.txt'])75- println()76- invoke(touch, args=['missing.txt'])77-78-79-File Opening Safety80--------------------81-82-The :class:`FileType` type has one problem it needs to deal with, and that83-is to decide when to open a file. The default behavior is to be84-"intelligent" about it. What this means is that it will open stdin/stdout85-and files opened for reading immediately. This will give the user direct86-feedback when a file cannot be opened, but it will only open files87-for writing the first time an IO operation is performed by automatically88-wrapping the file in a special wrapper.89-90-This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to91-the constructor. If the file is opened lazily, it will fail its first IO92-operation by raising an :exc:`FileError`.93-94-Since files opened for writing will typically immediately empty the file,95-the lazy mode should only be disabled if the developer is absolutely sure96-that this is intended behavior.97-98-Forcing lazy mode is also very useful to avoid resource handling99-confusion. If a file is opened in lazy mode, it will receive a100-``close_intelligently`` method that can help figure out if the file101-needs closing or not. This is not needed for parameters, but is102-necessary for manually prompting with the :func:`prompt` function as you103-do not know if a stream like stdout was opened (which was already open104-before) or a real file that needs closing.105-106-Starting with Click 2.0, it is also possible to open files in atomic mode by107-passing ``atomic=True``. In atomic mode, all writes go into a separate108-file in the same folder, and upon completion, the file will be moved over to109-the original location. This is useful if a file regularly read by other110-users is modified.added:docs/handling-files.rst+89 added
1+.. _handling-files:2+3+Handling Files4+================5+6+.. currentmodule:: click7+8+Click has built in features to support file and file path handling. Since files and files paths are recommended to be passed in as arguments, the examples use arguments.9+10+.. _file-args:11+12+File Arguments13+-----------------14+15+Click supports working with files with the :class:`File` type. Some notable features are:16+17+* Support for ``-`` to mean a special file that refers to stdin/stdout. This is common pattern for POSIX command line utilities, for example wget.18+* Deals with Unicode and bytes correctly for all versions of Python.19+20+Example:21+22+.. click:example::23+24+ @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)34+35+And what it does:36+37+.. click:run::38+39+ with isolated_filesystem():40+ invoke(inout, args=['-', 'hello.txt'], input=['hello'],41+ terminate_input=True)42+ invoke(inout, args=['hello.txt', '-'])43+44+File Path Arguments45+----------------------46+47+For handling paths, the :class:`Path` type is better than a string. Some notable features are:48+49+* It can run checks such as does the path exist or is the file executable.50+* It also handles formatting error messages with :func:`format_filename` so any undecodable bytes will be printed nicely.51+52+Example:53+54+.. click:example::55+56+ @click.command()57+ @click.argument('filename', type=click.Path(exists=True))58+ def touch(filename):59+ """Print FILENAME if the file exists."""60+ click.echo(click.format_filename(filename))61+62+And what it does:63+64+.. click:run::65+66+ with isolated_filesystem():67+ with open('hello.txt', 'w') as f:68+ f.write('Hello World!\n')69+ invoke(touch, args=['hello.txt'])70+ println()71+ invoke(touch, args=['missing.txt'])72+73+74+File Opening Behaviors75+-----------------------------76+77+The :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.78+79+File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:80+81+* A failure at first IO operation will happen by raising an :exc:`FileError`.82+* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will receive a83+ ``close_intelligently`` method that can help figure out if the file needs closing or not.84+ This is not needed for parameters, but is necessary for manually prompting with the :func:`prompt` function as you do not know if a stream like stdout was opened (which was already open85+ before) or a real file that needs closing.86+87+Since 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.88+89+It 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.modified:docs/index.rst+1 added-1 removed
73 unmodified lines74 options75 arguments76 commands77 prompts78- handling_files78+ handling-files79 documentation80 complex81 advanced82 testing27 unmodified linesmodified:src/click/types.py+7 added-4 removed
657 unmodified lines658 file lazily for reading, it is still opened temporarily for validation, but659 will not be held open until first IO. lazy is mainly useful when opening660 for writing to avoid creating the file until it is needed.661 662- Starting with Click 2.0, files can also be opened atomically in which663- case all writes go into a separate file in the same folder and upon664- completion the file will be moved over to the original location. This665- is useful if a file regularly read by other users is modified.662+ Files can also be opened atomically in which case all writes go into a663+ separate file in the same folder and upon completion the file will664+ be moved over to the original location. This is useful if a file665+ regularly read by other users is modified.666 667 See :ref:`file-args` for more information.668+669+ .. versionchanged:: 2.0670+ Added the ``atomic`` parameter.671 """672 673 name = "filename"674 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep419 unmodified lines