Python argparse flexibility option for true / false and string?

I have the following parser argument using argparse in a python 2.7 script:

parser = argparse.ArgumentParser(description=scriptdesc)
parser.add_argument("-l", "--list", help="Show current running sesssions", dest="l_list", type=str, default=None)

I want to be able to run:

./script -l and. / script -l session_1

So, the script returns either all sessions, or one session without an additional parameter, such as -s

However, I cannot find a way to do this in one argument.

+4
source share
1 answer

This is a bit of a hack since it relies on access to sys.argvoutside of any function argparse, but you can do something like:

import argparse
import sys


parser = argparse.ArgumentParser(description='')
parser.add_argument("-l", "--list", help="Show current running sesssions", dest="l_list", nargs='?')
args = parser.parse_args()

if args.l_list == None:
    if '-l' in sys.argv or '--list' in sys.argv:
        print('display all')
else:
    print('display %s only' %args.l_list)

, , . , 0 1 ( nargs='?'). -l, . , args l_list None ( ), -l , -l. , -l ( l_list == None -l --list sys.argv).

script test.py, .

$python test.py
$python test.py -l
display all
$python test.py -l session1
display session1 only

, argparse! sys.argv:

import argparse

parser = argparse.ArgumentParser(description='')
parser.add_argument("-l", "--list", help="Show current running sesssions", dest="l_list", nargs='?', default=-1)
args = parser.parse_args()

if args.l_list == None:
    print('display all')
elif args.l_list != -1:
    print('display %s only' %args.l_list)

, , default .add_argument , . - , None, , default. , , None, ( -1), :

$ python test.py
$ python test.py -l
display all
$ python test.py -l session1
display session1 only
+1

Source: https://habr.com/ru/post/1661389/


All Articles