Run python script with some of the argument that are optional

后端 未结 4 844
慢半拍i
慢半拍i 2021-02-06 04:53

I have gone through the sys documentation, however there is something that is still unclear to me. I have looked for some similar question on stackoverflow, but I h

4条回答
  •  梦谈多话
    2021-02-06 05:26

    While I endorse the argparse approach, here's a quick and dirty approach:

    arg1, arg2, arg3 = [None, False, []]
    if sys.argv[1:]:   # test if there are atleast 1 argument (beyond [0])
        arg1 = sys.argv[1]
        if sys.argv[2:]:
            arg2 = sys.argv[2]  # careful 'True' is a string, not a boolean
            arg3 = sys.argv[3:]  # rest
    

    Mostly I use this when I'm starting to add argument parsing to a script, and my choices of arguments hasn't matured. It's more suited to 'positionals' than 'optionals' (to use argparse terminology).

提交回复
热议问题