簡體   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