Git Product home page Git Product logo

Comments (2)

JAIDHEER007 avatar JAIDHEER007 commented on August 29, 2024

Prefixes of the command line argument are also valid.
For --name Its prefixes like --n --na --nam are all valid and they represent --name

To restrict this behavior:

Set allow_abbrev as False in ArgumentParser() method.

from argparse import ArgumentParser
import sys

parser = ArgumentParser(description='Say hello', allow_abbrev=False)

parser.add_argument('--name', '-n',metavar='str', help='The name to greet (default: World)', type=str, default='World')

# print(sys.argv)

args = parser.parse_args(sys.argv[1:])
print('Hello, {}!'.format(args.name))

Output:

python hello.py
Hello, World!

python hello.py --name Jaidheer
Hello, Jaidheer!

python hello.py -n Jaidheer
Hello, Jaidheer!

python hello.py --na Jaidheer

usage: hello.py [-h] [--name str]
hello.py: error: unrecognized arguments: --na Jaidheer

python hello.py --nam Jaidheer

usage: hello.py [-h] [--name str]
hello.py: error: unrecognized arguments: --na Jaidheer

allow_abbrev was introduced in python 3.5, so check for compatibility.

If a wrong command line argument is passed the program will terminate abruptly.

Useful Links

from tiny_python_projects.

kyclark avatar kyclark commented on August 29, 2024

I did not know about disallowing abbreviations. That is really useful! Thanks.

from tiny_python_projects.

Related Issues (18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.