Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give tuple via command line in python

I have to input few parameters via command line. such as tileGridSize, clipLimit etc via command line. This is what my code looks like;

#!/usr/bin/env python
import numpy as np
import cv2 as cv
import sys #import Sys. 
import matplotlib.pyplot as plt

img = cv.imread(sys.argv[1], 0) # reads image as grayscale
clipLimit = float(sys.argv[2])
tileGridSize = tuple(sys.argv[3])
clahe = cv.createCLAHE(clipLimit, tileGridSize)
cl1 = clahe.apply(img)

# show image
cv.imshow('image',cl1)
cv.waitKey(0)
cv.destroyAllWindows()

if I pass the arguments like,below (I want to give (8, 8) tuple);

python testing.py picture.jpg 3.0 8 8

I get the following error. I understand the error but dont know how to fix it.

TypeError: function takes exactly 2 arguments (1 given)
like image 587
Mass17 Avatar asked Oct 03 '20 17:10

Mass17


People also ask

How do you make a tuple in Python?

Creating a Tuple A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

How do you assign a tuple to a variable?

The tuple uses comma-separated values within round brackets or parentheses to store data. Tuples can be defined using any variable name and then assigning different values to the tuple inside the round brackets. The tuple is ordered, unchangeable, and allows duplicate values.


1 Answers

I suggest you look into argparse which is the standard package to handle command-lines but using strictly sys.argv:

import sys


print(sys.argv[1], float(sys.argv[2]), tuple(map(int, sys.argv[3:])))
$ python testing.py picture.jpg 3.0 8 8
> picture.jpg 3.0 (8, 8)

What happens:

  • sys.argv[3:] gets the list of all args including and after the 4th (index 3)
  • map(int, sys.argv[3:]) applies the int function to all items in the list
  • tuple(...) transforms map's generator into a proper tuple
like image 114
ted Avatar answered Sep 21 '22 12:09

ted