Skip to content
Myr

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

4 files+97 added−115 removed

deleted:docs/handling_files.rst-110 removed
1.. _handling-files:23Handling Files4================56.. currentmodule:: click78File and files paths are often passed in as arguments.910.. _file-args:1112File Arguments13--------------1415Since all the examples have already worked with filenames, it makes sense16to explain how to deal with files properly. Command line tools are more17fun if they work with files the Unix way, which is to accept ``-`` as a18special file that refers to stdin/stdout.1920Click supports this through the :class:`click.File` type which21intelligently handles files for you. It also deals with Unicode and bytes22correctly for all versions of Python so your script stays very portable.2324Example:2526.. click:example::2728 @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)3839And what it does:4041.. click:run::4243 with isolated_filesystem():44 invoke(inout, args=['-', 'hello.txt'], input=['hello'],45 terminate_input=True)46 invoke(inout, args=['hello.txt', '-'])4748File Path Arguments49-------------------5051In the previous example, the files were opened immediately. But what if52we just want the filename? The naïve way is to use the default string53argument type. The :class:`Path` type has several checks available which raise nice54errors if they fail, such as existence. Filenames in these error messages are formatted55with :func:`format_filename`, so any undecodable bytes will be printed nicely.5657Example:5859.. click:example::6061 @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))6667And what it does:6869.. click:run::7071 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'])777879File Opening Safety80-------------------8182The :class:`FileType` type has one problem it needs to deal with, and that83is 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/stdout85and files opened for reading immediately. This will give the user direct86feedback when a file cannot be opened, but it will only open files87for writing the first time an IO operation is performed by automatically88wrapping the file in a special wrapper.8990This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to91the constructor. If the file is opened lazily, it will fail its first IO92operation by raising an :exc:`FileError`.9394Since files opened for writing will typically immediately empty the file,95the lazy mode should only be disabled if the developer is absolutely sure96that this is intended behavior.9798Forcing lazy mode is also very useful to avoid resource handling99confusion. If a file is opened in lazy mode, it will receive a100``close_intelligently`` method that can help figure out if the file101needs closing or not. This is not needed for parameters, but is102necessary for manually prompting with the :func:`prompt` function as you103do not know if a stream like stdout was opened (which was already open104before) or a real file that needs closing.105106Starting with Click 2.0, it is also possible to open files in atomic mode by107passing ``atomic=True``. In atomic mode, all writes go into a separate108file in the same folder, and upon completion, the file will be moved over to109the original location. This is useful if a file regularly read by other110users is modified.
added:docs/handling-files.rst+89 added
1.. _handling-files:23Handling Files4================56.. currentmodule:: click78Click 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.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/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.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 what it does: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 string. Some notable features are:4849* 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.5152Example:5354.. click:example::5556 @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))6162And what it does:6364.. click:run::6566 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'])727374File Opening Behaviors75-----------------------------7677The :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.7879File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:8081* 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.8687Since 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.8889It 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 lines
74 options75 arguments76 commands77 prompts78 handling_files78 handling-files79 documentation80 complex81 advanced82 testing
27 unmodified lines
modified:src/click/types.py+7 added-4 removed
657 unmodified lines
658 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.661662 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.666667 See :ref:`file-args` for more information.668669 .. versionchanged:: 2.0670 Added the ``atomic`` parameter.671 """672673 name = "filename"674 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
419 unmodified lines