8

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

TheShun
  • 1,128
  • 6
  • 15
  • 21

2 Answers2

7

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.
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

The diffrence in cmd and argparse is that cmd is a "line-oriented command interpreter" while argparse is a parser for sys.argv.

Your example parses sys.argv that you pass while running your program and then if it gets the value you start a function and then quits.

argparse will only parse the sys.argv while running the program.

You could add some code to be able to work with the args you pass like a function or class or make in program menu that you could operate with raw_input. Example:

class Main():
  def __init__(self, create=None, send=None):
   if create:
     self.create(create)
   elif send:
     self.send(send)

    option = raw_input('What do you want to do now?')
    print option

  def create(self, val):
    print val

  def send(self, val):
    print val


if __name__ == "__main__":
  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()

  Main(args.create, args.send)

Other then that Python argparse and controlling/overriding the exit status code or python argparse - add action to subparser with no arguments? might help.

In the first it shows how you can override the quit and in the second how can you add subcommands or quitactions.

Community
  • 1
  • 1
Vizjerei
  • 1,000
  • 8
  • 15
  • Tes What i need is to be able to give command without quit the program. Like when you Click a button to do an action then Click another to do another action but without closing the program – TheShun Oct 12 '14 at 09:05