rojas rojas - 1 year ago 146
Python Question

How to make argparse work in executable program

I have a program command line which uses the argparse module.

import argparse

def run():
print 'Running'

def export():
print 'Exporting'

def argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument('run', action='store_true')
parser.add_argument('export', action='store_true')
return parser.parse_args()

args = argument_parser()

Now it works just fine when run from command line
> python run

However using
I've made an executable from it and if I open the main.exe file I got
too few arguments
error which is quite logical. But I want to be able to open (double click) main.exe (which open the comman line tool) and have the command line wait for my command (run or export in this case). Instead it just throws the error and quits.

Answer Source

Use the cmd module to create a shell.

You can then use cmd.Cmd() class you create to run single commands through the cmd.Cmd().onecmd() method; pass in the sys.argv command line, joined with spaces:

from cmd import Cmd
import sys

class YourCmdSubclass(Cmd):
    def do_run(*args):
        """Help text for run"""

    def do_export(*args):
        """Help text for export"""

    def do_exit(*args):
        return -1

if __name__ == '__main__':
    c = YourCmdSubclass()
    command = ' '.join(sys.argv[1:])
    if command:

Help is automatically provided by the help command.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download