本文介绍了python argparse在描述后打印用法文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用python argparse在描述文本后打印使用文本?我的 cmd 行 argparse 可以工作,但我想在使用信息之前打印版本信息.

版本:1.0用法:blahcmd [-h] [-help]一些可爱的帮助
解决方案

argparse 模块不提供任何添加序言"的选项.当显示帮助时,它总是usage:开头.您能做的最好的事情是使用 ArgumentParser 时的 code>usage 参数:

导入 argparseparser = argparse.ArgumentParser(usage='Any text you want\n')

请注意,帮助仍将以 usage: 开头.

一个可行的解决方法是使用 \r 开始 usage 消息:

>>>导入参数解析>>>用法 = '\r{}\nusage: %(prog)s etc.'.format('Version a b'.ljust(len('usage:')))>>>解析器 = argparse.ArgumentParser(usage=usage)>>>parser.parse_args(['-h'])版本 a b用途:等可选参数:-h, --help 显示此帮助信息并退出

我不认为 \r 的这种用法是可移植的.可能有一些终端这个技巧不起作用.我已经 ljust 编辑了版本字符串以确保当这个技巧起作用时,整个 usage: 字符串从字符串中消失,你不会得到像 这样的东西v1.2e: 使用短版本字符串时.

注意:您现在必须手动创建整个使用文本.

Is there a way to print usage text after the description text with python argparse? I have my cmd line argparse working, but i would like to print version info before usage info.

Edit:

version: 1.0

usage: blahcmd [-h] [-help]

some lovely help
解决方案

The argparse module does not provide any option to add a "prolog". When the help is displayed it always start with usage:. The best you can do is to customize the usage text adding the version number, using the usage parameter when you instantiate the ArgumentParser:

import argparse

parser = argparse.ArgumentParser(usage='Any text you want\n')

Note that the help will still start with usage:.

A dirty workaround that might work is to start the usage message with a \r:

>>> import argparse
>>> usage = '\r{}\nusage: %(prog)s etc.'.format('Version a b'.ljust(len('usage:')))
>>> parser = argparse.ArgumentParser(usage=usage)
>>> parser.parse_args(['-h'])
Version a b
usage:  etc.

optional arguments:
  -h, --help  show this help message and exit

I don't think that this usage of \r is portable. There are probably some terminals where this trick doesn't work. I've ljusted the version string to make sure that when the trick works, the whole usage: string disappears from string and you don't get things like v1.2e: when using short version strings.

Note: you must manually create the whole usage text now.

这篇关于python argparse在描述后打印用法文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 17:49