繁体   English   中英

如何在python中通过命令行给出元组

[英]how to give tuple via command line in python

我必须通过命令行输入几个参数。 例如 tileGridSize、clipLimit 等通过命令行。 这就是我的代码的样子;

#!/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()

如果我传递如下参数(我想给出 (8, 8) 元组);

python testing.py 图片.jpg 3.0 8 8

我收到以下错误。 我理解错误,但不知道如何修复它。

TypeError: function takes exactly 2 arguments (1 given)

我建议您查看argparse ,它是处理命令行的标准包,但严格使用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)

发生什么了:

  • sys.argv[3:]获取所有 args 的列表,包括 4th 之后(索引3
  • map(int, sys.argv[3:])int函数应用于列表中的所有项目
  • tuple(...)map的生成器转换为合适的元组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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