-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.

1 Answers1

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))
Stefan Jaritz
  • 1,999
  • 7
  • 36
  • 60
  • While this works, it'll always either get or set. Using `nargs='?'` with `const=...` would make it truly optional, if needed. – Ilja Everilä Mar 03 '17 at 09:30
  • You aren't taken into account the case when the user enters `--vol` without specifying a value for it. – elena Mar 03 '17 at 09:44
  • 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 – Stefan Jaritz Mar 03 '17 at 09:55
  • 1
    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. – Carlos Barreiro Mata Mar 03 '17 at 10:40