如何使 argparse 在可执行程序中工作 [英] How to make argparse work in executable program

查看:36
本文介绍了如何使 argparse 在可执行程序中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 argparse 模块的命令行脚本.

I have a command line script 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()
if args.run:
    run()
else:
    export()

现在从命令行运行时它工作得很好>python myfile.py run etc.

Now it works just fine when run from command line > python myfile.py run etc.

但是使用 pyinstaller 我已经从它制作了一个可执行文件,如果我打开 main.exe 文件,我会收到 too few arguments 错误,这是非常合乎逻辑的.但我希望能够打开(双击)main.exe(打开命令行工具)并让命令行等待我的命令(在这种情况下运行或导出).相反,它只是抛出错误并退出.

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. 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.

推荐答案

使用cmd 模块来创建一个shell.

Use the cmd module to create a shell.

然后您可以使用您创建的 cmd.Cmd() 类通过 cmd.Cmd().onecmd() 方法;传入sys.argv命令行,加入空格:

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"""
        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 命令自动提供.

Help is automatically provided by the help command.

这篇关于如何使 argparse 在可执行程序中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆