Automatically Type Cast Parameters In Python

后端 未结 6 2128
死守一世寂寞
死守一世寂寞 2020-12-30 04:37

Background:
I mostly run python scripts from the command line in pipelines and so my arguments are always strings that need to be type casted to the app

6条回答
  •  [愿得一人]
    2020-12-30 05:23

    If you're parsing arguments from the command line, you should use the argparse module (if you're using Python 2.7).

    Each argument can have an expected type so knowing what to do with it should be relatively straightforward. You can even define your own types.

    ...quite often the command-line string should instead be interpreted as another type, like a float or int. The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed. Common built-in types and functions can be used directly as the value of the type argument:

    parser = argparse.ArgumentParser()
    parser.add_argument('foo', type=int)
    parser.add_argument('bar', type=file)
    parser.parse_args('2 temp.txt'.split())
    >>> Namespace(bar=, foo=2)
    

提交回复
热议问题