Is there any way to work with command line parameters using the optparse or argparse library, which are not described in add_option? What would those who are described understood, and those that are not simply passed as a string or a list of parameters. Is it possible?

parser = optparse.OptionParser() parser.add_option ("-c", "--config", dest="config") 

and run the file with parameters

 start.py -c test -i 

    2 answers 2

    To recognize the known command line arguments described by the ArgumentParser.add_argument() method, and return the rest as a list, you can use the ArgumentParser.parse_known_args() method :

     >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='store_true') >>> parser.add_argument('bar') >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) 

    It is seen that the known and unknown options can be interleaved.

       from argparse import ArgumentParser p = ArgumentParser() p.add_argument('-f', '--Func') # которые описаны p.add_argument('items', nargs='*') # которые не описаны print(p.parse_args().__dict__.items()) >>> dict_items([('Func', None), ('items', [])])