How to modify attributes in a class in Python

Background Note

The module input parameter parsing is used in the project argparse, but when parsing, when the parameter value must be surrounded by double quotes, the double quotes at the two ends of the parameter value will affect the program execution, resulting in wrong results.

argparseAfter the module is parsed, the parameters and values ​​are stored in NameSpace, and used .to call, so it cannot be directly traversed and modified with for. And in the actual situation, there are multiple parameters, and it is too troublesome to deal with them separately, so they can be processed after analysis.

After trying several search engines, I couldn't find how to deal with it, so I looked at parse_known_argsthe source code, imitated and wrote it, and the result was correct. At other times, you may also encounter such a situation where you need to modify the attribute value in the class, so record it.

accomplish

import argparse
import sys
args = sys.argv[1:]
# args = ['--echo','"hello world"']
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--echo', type=str, default='', help='输出信息')
parsed, unparsed = parser.parse_known_args(args=args)
parsed_attr = parsed.__dict__
for attr in parsed_attr:
    value = parsed_attr[attr]
    if isinstance(attr, str):
        setattr(parsed, attr, str(value).strip('"'))
print(parsed)

parse_known_argssource code

    def parse_known_args(self, args=None, namespace=None):
        if args is None:
            # args default to the system args
            args = _sys.argv[1:]
        else:
            # make sure that args are mutable
            args = list(args)

        # default Namespace built from parser defaults
        if namespace is None:
            namespace = Namespace()

        # add any action defaults that aren't present
        for action in self._actions:
            if action.dest is not SUPPRESS:
                if not hasattr(namespace, action.dest):
                    if action.default is not SUPPRESS:
                        setattr(namespace, action.dest, action.default)

        # add any parser defaults that aren't present
        for dest in self._defaults:
            if not hasattr(namespace, dest):
                setattr(namespace, dest, self._defaults[dest])

        # parse the arguments and exit if there are any errors
        try:
            namespace, args = self._parse_known_args(args, namespace)
            if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
                args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
                delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
            return namespace, args
        except ArgumentError:
            err = _sys.exc_info()[1]
            self.error(str(err))

Guess you like

Origin blog.csdn.net/u012101384/article/details/129961100