简体   繁体   English

如何使 argparse 在可执行程序中工作

[英]How to make argparse work in executable program

I have a command line script which uses the argparse module.我有一个使用 argparse 模块的命令行脚本。

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()

Now it works just fine when run from command line > python myfile.py run etc.现在从命令行> python myfile.py run> python myfile.py run时它工作得很好。

However using pyinstaller 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.但是,使用pyinstaller我已经pyinstaller了一个可执行文件,如果我打开 main.exe 文件,我得到的too few arguments错误too few arguments ,这是非常合乎逻辑的。 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).但我希望能够打开(双击)main.exe(打开命令行工具)并让命令行等待我的命令(在这种情况下运行或导出)。 Instead it just throws the error and quits.相反,它只是抛出错误并退出。

Use the cmd module to create a shell.使用cmd模块创建一个 shell。

You can then use cmd.Cmd() class you create to run single commands through thecmd.Cmd().onecmd() method ;然后,您可以使用您创建的cmd.Cmd()类通过cmd.Cmd().onecmd()方法运行单个命令; pass in the sys.argv command line, joined with spaces:传入sys.argv命令行,加入空格:

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()

Help is automatically provided by the help command. help命令会自动提供help

只需使用./运行命令并使用通常的argparse输入,如下所示:

$ ./myfile -arg -arg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM