I am new to optparse of python and tried the following:
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:
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. 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, parserEssentially you are trying to process the argument from command line into its value by processing it through
plotfunction.I suspect you are trying to choose, action (such a
plot) to run from the command line, so perhaps more like:Note:
optparsehas been deprecated since 3.2, you should nowadays be usingargparse.