From f9d0531a8d575595b93ca862ad35b8fc573927c1 Mon Sep 17 00:00:00 2001 From: donBarbos Date: Fri, 14 Mar 2025 17:15:35 +0400 Subject: gh-93096: Update and document `pickle` CLI (#131097) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> Co-authored-by: Victor Stinner Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> --- Doc/library/cmdline.rst | 2 +- Doc/library/pickle.rst | 24 ++++++++++++++++++++++++ Lib/pickle.py | 21 +++++++++------------ 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/Doc/library/cmdline.rst b/Doc/library/cmdline.rst index a000eb2..25abee8 100644 --- a/Doc/library/cmdline.rst +++ b/Doc/library/cmdline.rst @@ -25,7 +25,7 @@ The following modules have a command-line interface. * :ref:`json ` * :ref:`mimetypes ` * :mod:`pdb` -* :mod:`pickle` +* :ref:`pickle ` * :ref:`pickletools ` * :mod:`platform` * :mod:`poplib` diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst index 66aa51c..007c9fe 100644 --- a/Doc/library/pickle.rst +++ b/Doc/library/pickle.rst @@ -1210,6 +1210,30 @@ The following example reads the resulting pickled data. :: .. pickletools.optimize() or the gzip module). +.. _pickle-cli: + +Command-line interface +---------------------- + +The :mod:`pickle` module can be invoked as a script from the command line, +it will display contents of the pickle files. However, when the pickle file +that you want to examine comes from an untrusted source, ``-m pickletools`` +is a safer option because it does not execute pickle bytecode, see +:ref:`pickletools CLI usage `. + +.. code-block:: bash + + python -m pickle pickle_file [pickle_file ...] + +The following option is accepted: + +.. program:: pickle + +.. option:: pickle_file + + A pickle file to read, or ``-`` to indicate reading from standard input. + + .. seealso:: Module :mod:`copyreg` diff --git a/Lib/pickle.py b/Lib/pickle.py index 8f7406d..efcdcbe 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -1909,20 +1909,17 @@ except ImportError: if __name__ == "__main__": import argparse + import pprint parser = argparse.ArgumentParser( description='display contents of the pickle files') parser.add_argument( 'pickle_file', - nargs='*', help='the pickle file') + nargs='+', help='the pickle file') args = parser.parse_args() - if not args.pickle_file: - parser.print_help() - else: - import pprint - for fn in args.pickle_file: - if fn == '-': - obj = load(sys.stdin.buffer) - else: - with open(fn, 'rb') as f: - obj = load(f) - pprint.pprint(obj) + for fn in args.pickle_file: + if fn == '-': + obj = load(sys.stdin.buffer) + else: + with open(fn, 'rb') as f: + obj = load(f) + pprint.pprint(obj) -- cgit v0.12