简体   繁体   English

python 的 Optparse

[英]Optparse of python

I am new to optparse of python and tried the following:我是 python optparse 的新手,并尝试了以下操作:

def plot():
    x=[1,2,3]
    y=[4,5,6]
    plt.plot(x,y)
    plt.savefig('trial.pdf')

parser=OptionParser()
parser.add_option("-p", "--plot", action="callback", callback=plot)
(options, args)=parser.parse_args()

I typed python3 parse.py -p in the terminal and it gave:我在终端中输入了python3 parse.py -p ,它给出了:

Traceback (most recent call last):
  File "firstparse.py", line 15, in <module>
    (options, args)=parser.parse_args()
  File "/usr/lib/python3.5/optparse.py", line 1386, in parse_args
    stop = self._process_args(largs, rargs, values)
  File "/usr/lib/python3.5/optparse.py", line 1430, in _process_args
    self._process_short_opts(rargs, values)
  File "/usr/lib/python3.5/optparse.py", line 1535, in _process_short_opts
    option.process(opt, value, values, self)
  File "/usr/lib/python3.5/optparse.py", line 784, in process
    self.action, self.dest, opt, value, values, parser)
  File "/usr/lib/python3.5/optparse.py", line 804, in take_action
    self.callback(self, opt, value, parser, *args, **kwargs)
TypeError: plot() takes 0 positional arguments but 4 were given

I do not understand well about the positional arguments error.我不太了解位置 arguments 错误。 Could anyone tell me where I wrong?谁能告诉我我错在哪里?

Check out the documentation :查看文档

When using callback , you supply a function that is used to process the incoming argument, this function is called with four arguments: option, opt_str, value, parser使用callback时,您提供一个 function 用于处理传入参数,此 function 使用四个 arguments 调用: option, opt_str, value, parser

option

is the Option instance that's calling the callback是调用回调的 Option 实例

opt_str

is the option string seen on the command-line that's triggering the callback...是在触发回调的命令行上看到的选项字符串...

value

is the argument to this option seen on the command-line...是在命令行上看到的此选项的参数...

parser

is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes...是驱动整个事情的 OptionParser 实例,主要是因为您可以通过它的实例属性访问一些其他有趣的数据...

Essentially you are trying to process the argument from command line into its value by processing it through plot function.本质上,您正在尝试通过plot function 将参数从命令行处理为其值。

I suspect you are trying to choose, action (such a plot ) to run from the command line, so perhaps more like:我怀疑您正在尝试选择从命令行运行的操作(例如plot ),因此可能更像:

parser=ArgumentParser()
parser.add_argument("-p", "--plot", action="store_true")
args = parser.parse_args()
if args.plot is True:
    plot()

Note: optparse has been deprecated since 3.2, you should nowadays be using argparse .注意: optparse自 3.2 以来已被弃用,您现在应该使用argparse

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

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