How to iterate over arguments

后端 未结 6 602
生来不讨喜
生来不讨喜 2020-12-08 09:22

I have such script:

import argparse

parser = argparse.ArgumentParser(
                description=\'Text file conversion.\'
                )
parser.add_arg         


        
6条回答
  •  执念已碎
    2020-12-08 10:17

    Parsing the _actions from your parser seems like a decent idea. Instead of running parse_args() and then trying to pick stuff out of your Namespace.

    import argparse
    
    parser = argparse.ArgumentParser(
                    description='Text file conversion.')
    parser.add_argument("inputfile", help="file to process", type=str)
    parser.add_argument("-o", "--out", default="output.txt",
                    help="output name")
    parser.add_argument("-t", "--type", default="detailed",
                    help="Type of processing")
    options = parser._actions
    for k in options:
        print(getattr(k, 'dest'), getattr(k, 'default'))  
    

    You can modify the 'dest' part to be 'choices' for example if you need the preset defaults for a parameter in another script (by returning the options in a function for example).

提交回复
热议问题