Mass17
Mass17

Reputation: 1605

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)

Upvotes: 5

Views: 505

Answers (1)

ted
ted

Reputation: 14724

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

Upvotes: 7

Related Questions