How to make argparse work in executable program
<p>I have a program command line which uses the argparse module.</p>

<pre><code>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()
if args.run:
    run()
else:
    export()
</code></pre>

<p>Now it works just fine when run from command line <code>&gt; python myfile.py run</code> etc. </p>

<p>However using <code>pyinstaller</code> I've made an executable from it and if I open the main.exe file I got <code>too few arguments</code> 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.</p>

<p>Use the <a href="https://docs.python.org/3/library/cmd.html" rel="nofollow"><code>cmd</code> module</a> to create a shell.</p>

<p>You can then use <code>cmd.Cmd()</code> class you create to run single commands through the <a href="https://docs.python.org/3/library/cmd.html#cmd.Cmd.onecmd" rel="nofollow"><code>cmd.Cmd().onecmd()</code> method</a>; pass in the <code>sys.argv</code> command line, joined with spaces:</p>

<pre><code>from cmd import Cmd
import sys

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

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

    def do_exit(*args):
        return -1


if __name__ == '__main__':
    c = YourCmdSubclass()
    command = ' '.join(sys.argv[1:])
    if command:
        sys.exit(c.onecmd(command))
    c.cmdloop()
</code></pre>

<p>Help is automatically provided by the <code>help</code> command.</p>

python argparse pyinstaller