Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'int' object is not subscriptable when I try to pass three arguments in parse.parse_args()

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help="Path to input image", required=True)
ap.add_argument("-p", "--pivot-point", help="Pivot point coordinates x, y separated by comma (,)", required=True)
ap.add_argument("-s", "--scale", help="Scale to zoom", type = int, required=True)
args = vars(ap.parse_args(['image.jpeg', '(144,72)', 3]))

Hello,

I am trying to pass an image in the arguments to pivot it and scale it for zooming through argparse.

But I'm getting the following error:

Please, let me know what you're doing wrong.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-131-c7157827dce9> in <module>()
      3 ap.add_argument("-p", "--pivot-point", help="Pivot point coordinates x, y separated by comma (,)", required=True)
      4 ap.add_argument("-s", "--scale", help="Scale to zoom", type = int, required=True)
----> 5 args = vars(ap.parse_args(['image.jpeg', '(144,72)', 3]))

~/anaconda3/lib/python3.6/argparse.py in parse_args(self, args, namespace)
   1728     # =====================================
   1729     def parse_args(self, args=None, namespace=None):
-> 1730         args, argv = self.parse_known_args(args, namespace)
   1731         if argv:
   1732             msg = _('unrecognized arguments: %s')

~/anaconda3/lib/python3.6/argparse.py in parse_known_args(self, args, namespace)
   1760         # parse the arguments and exit if there are any errors
   1761         try:
-> 1762             namespace, args = self._parse_known_args(args, namespace)
   1763             if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
   1764                 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))

~/anaconda3/lib/python3.6/argparse.py in _parse_known_args(self, arg_strings, namespace)
   1801             # and note the index if it was an option
   1802             else:
-> 1803                 option_tuple = self._parse_optional(arg_string)
   1804                 if option_tuple is None:
   1805                     pattern = 'A'

~/anaconda3/lib/python3.6/argparse.py in _parse_optional(self, arg_string)
   2087 
   2088         # if it doesn't start with a prefix, it was meant to be positional
-> 2089         if not arg_string[0] in self.prefix_chars:
   2090             return None
   2091 

TypeError: 'int' object is not subscriptable
like image 969
Gagan GM Avatar asked Sep 06 '25 03:09

Gagan GM


2 Answers

The parser normally handles sys.argv[1:] which is a list of strings generated by the shell. Testing with your own list requires strings as well. Note the use of '3' instead of 3.

In [182]: ap.parse_args(['image.jpeg', '(144,72)', '3'])
usage: ipython3 [-h] -i IMAGE -p PIVOT_POINT -s SCALE
ipython3: error: the following arguments are required: -i/--image, -p/--pivot-point, -s/--scale
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

Now it gives the standardized argparse error with usage and useful diagnosis.

If we provide the short option flags that you told it to expect:

In [183]: ap.parse_args(['-i','image.jpeg', '-p','(144,72)', '-s' '3'])
Out[183]: Namespace(image='image.jpeg', pivot_point='(144,72)', scale=3)
In [184]: vars(_)
Out[184]: {'image': 'image.jpeg', 'pivot_point': '(144,72)', 'scale': 3}

Or we can use split to get a clearer idea of what the proper commandline will look like:

In [186]: ap.parse_args("-i image.jpeg -p (144,72) -s 3".split())
Out[186]: Namespace(image='image.jpeg', pivot_point='(144,72)', scale=3)

Since you have defined -s as type=int, it converts the string '3' into an integer.

For -p you might want to try nargs=2, allowing you to use '-p 144 72'.

With

ap.add_argument("-p", "--pivot-point", nargs=2, metavar=('x','y'), 
    type=int, help="Pivot point coordinates")

I get:

In [196]: ap.print_help()
usage: ipython3 [-h] -i IMAGE -p x y -s SCALE

optional arguments:
  -h, --help            show this help message and exit
  -i IMAGE, --image IMAGE
                        Path to input image
  -p x y, --pivot-point x y
                        Pivot point coordinates
  -s SCALE, --scale SCALE
                        Scale to zoom

In [197]: ap.parse_args("-i image.jpeg -p 144 72 -s 3".split())
Out[197]: Namespace(image='image.jpeg', pivot_point=[144, 72], scale=3)
like image 105
hpaulj Avatar answered Sep 07 '25 17:09

hpaulj


All of the elements in the list that you pass into parse_args need to be strings, it's up to the argument parser to interpret the strings as the type that you set.

like image 28
camstu Avatar answered Sep 07 '25 17:09

camstu