-1

I know get values from argsparse like:

parser.add_argument('--volume', help='Ejecuta una aplicacion cualquiera')

Also I know if the argument is True or False with this:

parser.add_argument('--getVolume', action='store_true', help='Ejecuta una aplicacion cualquiera')

But I don't Know use both some time, because I want use the argument like getter-setter. For example if I dont write a number the program return the current volume and if I write a number the app set this volume to the robot.

python app.py --volume      # Return the current volume
python app.py --volume 80   # Set the volume to the 80%

Thank you very much,

Carlos.

2
  • In addition to the link, use such a default that you can then decide whether to display or update the volume. Commented Mar 3, 2017 at 9:24
  • docs.python.org/3/library/argparse.html Look example 16.4.3.2 Commented Mar 3, 2017 at 9:25

1 Answer 1

0

You can use the default value for the set/get checking. Some pseudo code:

parser.add_argument("-v", "--vol", dest="vol",  
    help="the volume [default: %(default)s]",
    default=None
)
args = parser.parse_args()

if None == args.vol:
    print(str(getVolume()))
else:
    setVolume(float(args.vol))
Sign up to request clarification or add additional context in comments.

4 Comments

While this works, it'll always either get or set. Using nargs='?' with const=... would make it truly optional, if needed.
You aren't taken into account the case when the user enters --vol without specifying a value for it.
this is a pseudo code. Feel free to change it. I would serve that problem in the way when no params are put on the commandline the programm is in get mode. If there is a volume parameter it is in set mode
Thank you! The problem was that of this way I need if the argument volume exists. I solved my problem with: parser.add_argument('--volume', help='Ejecuta una aplicacion cualquiera', nargs='?', const='get'). Of this form if the argument volume don't exist the value is None, if the argument volume exist but it haven't value the value is 'get'. Thank you, very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.