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, parser
optionis the Option instance that’s calling the callback
opt_stris the option string seen on the command-line that’s triggering the callback...
valueis the argument to this option seen on the command-line...
parseris the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes...
Essentially you are trying to process the argument from command line into its value by processing it through plot function.
I suspect you are trying to choose, action (such a plot) to run from the command line, so perhaps more like:
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.