• =?UTF-8?Q?Re=3a_argparse_=e2=80=94_adding_a_--version_flag_in_the_f?= =

    From Mats Wichmann@21:1/5 to Skip Montanaro on Sun Nov 27 17:29:34 2022
    On 11/27/22 16:40, Skip Montanaro wrote:
    I have a script to which I'd like to add a --version flag. It should print the version number then exit, much in the same way --help prints the help text then exits. I haven't been able to figure that out. I always get a complaint about the required positional argument.

    I think I could use something like nargs='*', but that would push off detection of the presence of the positional arg to the application.
    Shouldn't I be able to tell argparse I'm going to process --verbose, then exit?

    ummm, hate to say this, but have you checked the documentation? this
    case is supported using an action named 'version' without doing very much.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Loris Bennett@21:1/5 to Mats Wichmann on Mon Nov 28 07:59:44 2022
    Mats Wichmann <mats@wichmann.us> writes:

    On 11/27/22 16:40, Skip Montanaro wrote:
    I have a script to which I'd like to add a --version flag. It should print >> the version number then exit, much in the same way --help prints the help
    text then exits. I haven't been able to figure that out. I always get a
    complaint about the required positional argument.
    I think I could use something like nargs='*', but that would push
    off
    detection of the presence of the positional arg to the application.
    Shouldn't I be able to tell argparse I'm going to process --verbose, then
    exit?

    ummm, hate to say this, but have you checked the documentation? this
    case is supported using an action named 'version' without doing very
    much.

    I hadn't noticed the action 'version'. I just use

    parser.add_argument(
    "-v", "--version", action="store_true", dest="version",
    help="print version"
    )

    ...

    if args.version:
    print(f"Version {my_module.__version__}")
    sys.exit(0)

    where the version is specified in a pyproj.toml file and __init__.py
    contains

    try:
    import importlib.metadata as importlib_metadata
    except ModuleNotFoundError:
    import importlib_metadata

    __version__ = importlib_metadata.version(__name__)

    I use poetry to then build the corresponding versioned package.

    What am I missing by not using the action 'version'? Do I just save
    having to explicitly test for the version arg?

    Cheers,

    Loris

    --
    This signature is currently under constuction.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)