如何在python中实现命令行函数的选项/参数
我的python版本是2.4.3 现在,我正在从python为CD播放器开发一个带有cmd模块的CLI。我有一些类,比如CDContainer(使用addCD、removeCD等方法),CD(使用play、stop、pause等方法)。现在,我想为命令添加一些选项,如果选项输入不正确,CLI可能会返回有关错误输入类型或错误值的正确信息。e、 例如,我想要“addcd——曲目3——cdname thriller”。我现在做的是通过获取所有参数,将其拆分,并将其分配给相关变量,如下所示 我的问题是在python中,是否有一些模块便于我的案例解析和分析选项或参数 修订:好的,我编辑它,感谢gclj5的评论如何在python中实现命令行函数的选项/参数,python,command-line,command-line-arguments,Python,Command Line,Command Line Arguments,我的python版本是2.4.3 现在,我正在从python为CD播放器开发一个带有cmd模块的CLI。我有一些类,比如CDContainer(使用addCD、removeCD等方法),CD(使用play、stop、pause等方法)。现在,我想为命令添加一些选项,如果选项输入不正确,CLI可能会返回有关错误输入类型或错误值的正确信息。e、 例如,我想要“addcd——曲目3——cdname thriller”。我现在做的是通过获取所有参数,将其拆分,并将其分配给相关变量,如下所示 我的问题是在
import cmd
class CDContainerCLI(cmd.Cmd):
def do_addcd(self, line):
args=line.split()
parser = OptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
parser.add_option("-n", "--cdname", dest="cd_name", type="string",
help="CD name")
(options, positional_args) = parser.parse_args(args)
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
如果可能的话,您能写一些代码示例,只是为了演示如何做吗
非常感谢
我的问题是在python中,是否有一些模块便于我的案例解析和分析选项或参数
是的,是的
如果您已经熟悉C中的getopt库,尽管不太容易使用,但如果您还不习惯它的话
我的问题是在python中,是否有一些模块便于我的案例解析和分析选项或参数
是的,是的
如果您已经熟悉C中的getopt库,尽管不太容易使用,但如果您还不习惯它。根据您的Python版本,您应该查看(自版本2.3起,自版本2.7起弃用)或(自版本2.7起) 一些使用optpasse的示例代码(
line
是您在CLI中从stdin读取的字符串):
此解析器仅处理“addcd”命令。例如,对于更多命令,您可以使用字典中以命令名为键的几个OptionParser
对象。您可以像这样解析选项:
(options, args) = parsers[args[0]].parse_args(args[1:])
有关更多信息,请参阅optparse的文档。例如,输出使用信息非常容易。还有一个可用的版本。根据您的Python版本,您应该查看(自版本2.3起,自版本2.7起弃用)或(自版本2.7起) 一些使用optpasse的示例代码(
line
是您在CLI中从stdin读取的字符串):
此解析器仅处理“addcd”命令。例如,对于更多命令,您可以使用字典中以命令名为键的几个OptionParser
对象。您可以像这样解析选项:
(options, args) = parsers[args[0]].parse_args(args[1:])
有关更多信息,请参阅optparse的文档。例如,输出使用信息非常容易。还有一个可用的。这是几个月前我和同事学习模块时编写的演示脚本。它说明了模块的几个行为和功能:
import sys
import argparse
def parse_command_line():
# Define our argument parser.
ap = argparse.ArgumentParser(
description = 'This is a demo app for the argparse module.',
epilog = 'This text will appear after options.',
usage = '%(prog)s [options]', # Auto-generated by default.
add_help = False, # Default is True.
)
# A grouping of options in the help text.
gr = ap.add_argument_group('Required arguments')
# A positional argument. This is indicated by the absense
# of leading minus signs.
gr.add_argument(
'task',
choices = ['get', 'put'],
help = 'Task to be performed.', # Help text about an option.
metavar = 'TASK', # Placeholder to be used in an option's help text.
# The default in this case would be "{get,put}".
)
# Another group.
gr = ap.add_argument_group('Common options')
# A basic option.
gr.add_argument(
'-s', '--subtask',
action = 'store', # This is the default.
# One value will be stored, as a string,
# in opt.subtask
)
# A required option, with type conversion.
gr.add_argument(
'-u', '--user',
required = True, # Options can be made mandatory.
# However, positional arguments can't be made optional.
type = int, # Convert opt.user to an integer.
# By default, it would be a string.
)
# A flag option.
gr.add_argument(
'--overwrite',
dest = 'clobber', # Store in opt.clobber rather than opt.overwrite.
action = 'store_true', # If option is supplied, opt.clobber == True.
)
# Another group.
gr = ap.add_argument_group('Some other options')
# An option with multiple values.
gr.add_argument(
'--datasets',
metavar = 'DATASET', # Default would be DATASETS.
nargs = '+', # If option is used, it takes 1 or more arguments.
# Will be stored as a list in opt.datasets.
help = "The datasets to use for frobnication.",
)
# An option with a specific N of values.
gr.add_argument(
'--bar',
nargs = 1, # Takes exactly one argument. Differs from a basic
# option because opt.bar will be a list rather
# than a string.
default = [], # Default would be None.
)
# A file option.
gr.add_argument(
'--log',
type = argparse.FileType('w'), # Will open a file for writing.
default = sys.stdout,
help = 'Log file (default: STDOUT)',
)
# Another group.
gr = ap.add_argument_group('Program information')
# A version option.
gr.add_argument(
'-v', '--version',
action = 'version', # Will display version text and exit.
version = 'argparse_demo v1.2.0', # The version text.
)
# A help option.
gr.add_argument(
'-h', '--help',
action = 'help', # Will display help text and exit.
)
# Parse the options.
# If given no arguments, parse_args() works with sys.argv[1:].
# And the object it returns will be of type Namespace.
opt = ap.parse_args()
return opt
command_lines = [
'argparse_demo.py put -u 1',
'argparse_demo.py get -u 234 --over --data a b c --bar XYZ -s munch --log _log.txt',
'argparse_demo.py -h', # Will exit() here.
]
for c in command_lines:
sys.argv = c.split()
opt = parse_command_line()
print opt
这是我几个月前写的一个演示脚本,当时我和同事正在学习这个模块。它说明了模块的几个行为和功能:
import sys
import argparse
def parse_command_line():
# Define our argument parser.
ap = argparse.ArgumentParser(
description = 'This is a demo app for the argparse module.',
epilog = 'This text will appear after options.',
usage = '%(prog)s [options]', # Auto-generated by default.
add_help = False, # Default is True.
)
# A grouping of options in the help text.
gr = ap.add_argument_group('Required arguments')
# A positional argument. This is indicated by the absense
# of leading minus signs.
gr.add_argument(
'task',
choices = ['get', 'put'],
help = 'Task to be performed.', # Help text about an option.
metavar = 'TASK', # Placeholder to be used in an option's help text.
# The default in this case would be "{get,put}".
)
# Another group.
gr = ap.add_argument_group('Common options')
# A basic option.
gr.add_argument(
'-s', '--subtask',
action = 'store', # This is the default.
# One value will be stored, as a string,
# in opt.subtask
)
# A required option, with type conversion.
gr.add_argument(
'-u', '--user',
required = True, # Options can be made mandatory.
# However, positional arguments can't be made optional.
type = int, # Convert opt.user to an integer.
# By default, it would be a string.
)
# A flag option.
gr.add_argument(
'--overwrite',
dest = 'clobber', # Store in opt.clobber rather than opt.overwrite.
action = 'store_true', # If option is supplied, opt.clobber == True.
)
# Another group.
gr = ap.add_argument_group('Some other options')
# An option with multiple values.
gr.add_argument(
'--datasets',
metavar = 'DATASET', # Default would be DATASETS.
nargs = '+', # If option is used, it takes 1 or more arguments.
# Will be stored as a list in opt.datasets.
help = "The datasets to use for frobnication.",
)
# An option with a specific N of values.
gr.add_argument(
'--bar',
nargs = 1, # Takes exactly one argument. Differs from a basic
# option because opt.bar will be a list rather
# than a string.
default = [], # Default would be None.
)
# A file option.
gr.add_argument(
'--log',
type = argparse.FileType('w'), # Will open a file for writing.
default = sys.stdout,
help = 'Log file (default: STDOUT)',
)
# Another group.
gr = ap.add_argument_group('Program information')
# A version option.
gr.add_argument(
'-v', '--version',
action = 'version', # Will display version text and exit.
version = 'argparse_demo v1.2.0', # The version text.
)
# A help option.
gr.add_argument(
'-h', '--help',
action = 'help', # Will display help text and exit.
)
# Parse the options.
# If given no arguments, parse_args() works with sys.argv[1:].
# And the object it returns will be of type Namespace.
opt = ap.parse_args()
return opt
command_lines = [
'argparse_demo.py put -u 1',
'argparse_demo.py get -u 234 --over --data a b c --bar XYZ -s munch --log _log.txt',
'argparse_demo.py -h', # Will exit() here.
]
for c in command_lines:
sys.argv = c.split()
opt = parse_command_line()
print opt
嗨,gclj5,谢谢你的回答。我使用的是2.4.3。我听说过这个optpasse,但我不知道如何在代码中使用它。e、 g.如何将其集成到addcd功能中?我应该在哪里以及如何添加它?我不知道你的程序的确切结构,所以我不能确切地告诉你在哪里添加它。但是我添加了一些示例代码来说明optparse包的用法。一般的想法是让CLI解析代码使用解析后的选项调用相应的函数。您好,gclj5,非常感谢您的代码。它是args[0:],而不是args[1:],因为args被用作方法的输入。我修改了我原来帖子中的代码。但仍然存在一些问题。当出现一些异常(错误类型或缺少选项)时,整个程序将退出此optionparse,而不是仅针对相关方法退出。我们如何解决这个问题?只需捕获异常并自行处理错误(通知用户并退出该方法)。另请参见OptPass教程中的部分。顺便说一句,您最好在您的案例中直接使用
args
(不使用[0://code>)。您好,gclj5,因此如果我捕获异常并自行处理错误,则根本不需要OptPass。是这样吗?这有点让人失望,就差那么一点点就有了方便的东西,但最后,我还是用不上。嗨,gclj5,谢谢你的回答。我使用的是2.4.3。我听说过这个操作分析,但我不知道如何使用它与代码。e、 g.如何将其集成到addcd功能中?我应该在哪里以及如何添加它?我不知道你的程序的确切结构,所以我不能确切地告诉你在哪里添加它。但是我添加了一些示例代码来说明optparse包的用法。一般的想法是让CLI解析代码使用解析后的选项调用相应的函数。您好,gclj5,非常感谢您的代码。它是args[0:],而不是args[1:],因为args被用作方法的输入。我修改了我原来帖子中的代码。但仍然存在一些问题。当出现一些异常(错误类型或缺少选项)时,整个程序将退出此optionparse,而不是仅针对相关方法退出。我们如何解决这个问题?只需捕获异常并自行处理错误(通知用户并退出该方法)。另请参见OptPass教程中的部分。顺便说一句,您最好在您的案例中直接使用args
(不使用[0://code>)。您好,gclj5,因此如果我捕获异常并自行处理错误,则根本不需要OptPass。是这样吗?这是有点令人失望,只是这么接近有一些方便,但在最后,我仍然无法使用它。