python - Using Argparse for Dictionary -


i want read 1 of items list of videos. video reading , display code following. code working fine.

import cv2   def videoreading(vid):      cap = cv2.videocapture(vid)     while true:         ret, frame = cap.read()         cv2.imshow('video', frame)         if cv2.waitkey(1) & 0xff == ord('q'):             break     cap.release()     cv2.destroyallwindows() 

since i've large number of videos , i'm calling code through command line, writing entire video name cumbersome. created dictionary. here given example of 2:

{"video1.mp4": 1, 'video2.mp4': 2} 

now i'm using following code call video using value 1 or 2, rather video name. code following:

def main():      videofiles= ["video1.mp4", "video2.mp4"]     videofilesindicator = [1, 2]      model_list = {}     in range(len(videofiles)):         model_list[videofiles[i]] = videofilesindicator[i]      print(model_list)     def convertvalues(value):         return model_list.get(value, value)      parser = argparse.argumentparser()     group = parser.add_mutually_exclusive_group()       group.add_argument("-v", "--video", = "add video file name of format", type = convertvalues,\                      choices = [1,2], default = 1)      args =parser.parse_args()      return videoreading(args.video)    if __name__ == "__main__":      main() 

now when i'm running code in cmd "python videoreading.py -v 2", it's throwing me following error.

error: argument -v/--video: invalid choice: '2' (choose 1, 2)

i'm not understanding why i'm getting error. i'm following this post build program.

your dictionary backwards; want map number file name, when enter number, file name can returned. there's no need provide default value convertvalues, because using choices limit allowable inputs valid keys of dict.

def main():      video_files = ["video1.mp4", "video2.mp4"]      model_list = dict(enumerate(video_files, start=1))      print(model_list)       parser = argparse.argumentparser()     group = parser.add_mutually_exclusive_group()      group.add_argument("-v", "--video",                         help="add video file name of format",                        type=lambda str: model_list[int(str)],                        choices=model_list.values())      args = parser.parse_args()      return videoreading(args.video) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -