简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM