Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make my python command line program interactive with argparse

i'm trying to make my python program interactive in command line, user should be able to do stuff like :

python myprogram.py --create

then

python myprogram.py --send

The problem in this when is that the program stop and restart each time so i lose my variable and object that i created with the first command.

I'm using argparse on this way:

parser = argparse.ArgumentParser()
parser.add_argument('-c','--create' ,help='',action='store_true')
parser.add_argument('-s','--send',help='',action='store_true')
args = parser.parse_args()

if args.create:
    create()
elif args.send :
    send()

I don't want to stop the program between the command, how to do this ?

example : https://coderwall.com/p/w78iva

like image 432
TheShun Avatar asked Oct 12 '14 06:10

TheShun


People also ask

How does Argparse work in Python?

The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.


1 Answers

Here's a simple interactive script. I use argparse to parse the input lines, but otherwise it is not essential to the action. Still it can be an handy way of adding options to your 'create' command. For example, ipython uses argparse to handle its %magic commands:

import argparse
parser = argparse.ArgumentParser(prog='PROG', description='description')
parser.add_argument('cmd', choices=['create','delete','help','quit'])

while True:
    astr = raw_input('$: ')
    # print astr
    try:
        args = parser.parse_args(astr.split())
    except SystemExit:
        # trap argparse error message
        print 'error'
        continue
    if args.cmd in ['create', 'delete']:
        print 'doing', args.cmd
    elif args.cmd == 'help':
        parser.print_help()
    else:
        print 'done'
        break

This could be stripped down to the while loop, the raw_input line, and your own evaluation of the astr variable.

The keys to using argparse here are:

  • parse_args can take a list of strings (the result of split()) instead of using the default sys.argv[1:].
  • if parse_args sees a problem (or '-h') it prints a message and tries to 'exit'. If you want to continue, you need to trap that error, hence the try block.
  • the output of parse_args is a simple namespace object. You access the arguments as attributes.
  • you could easily substitute your own parser.
like image 54
hpaulj Avatar answered Oct 31 '22 15:10

hpaulj