如何检查命令行参数的参数处理

问题描述 投票:0回答:1

我正在尝试创建一个简单的脚本,它将使用 exif 库从图像文件中提取数据信息。我的想法是输入一个图像文件作为参数,然后我的代码将打印出我请求的所有 exif 数据,但是当我尝试测试参数处理时,我总是遇到错误。

例如,如果我根本不输入图像文件,我想让我的程序进行测试。而且我还希望我的程序检查我输入的文件是否不是图像文件,但我不断收到值和索引错误。有更好的方法吗?

这是我尝试过的:

#! /usr/bin/python3

from exif import Image
import piexif
import exif
import sys

if __name__ == "__main__":
    # load an image through PIL's Image object
    image = Image(sys.argv[1])

    try:
        image = Image(sys.argv[1])
        print("Source File: " + str(sys.argv[1]))
        print("Make: " + image.make)
        print("Model: " + image.model)
        print("Original Date/Time: " + image.datetime)
        print(image.gps_latitude)
        print(image.gps_longitude)
    except (ValueError):
        print('No image file has been specified!')
    except (IndexError):
        print('No File Located')

输入:

python3 test1.py file1

输出:

Source File: file1
Make: Apple
Model: iPhone 4S
Original Date/Time: 2012:02:07 08:17:05
(30.0, 5.0, 9.6)
(94.0, 5.0, 57.6)

输入:

python3 test1.py file**2

输出:

Traceback (most recent call last):
  File "/home/kali/Desktop/test1.py", line 12, in <module>
    image = Image(sys.argv[1])
  File "/home/kali/.local/lib/python3.10/site-packages/exif/_image.py", line 80, in __init__
    raise ValueError("expected file object, file path as str, or bytes")
ValueError: expected file object, file path as str, or bytes

输入:

python3 test1.py

输出:

Traceback (most recent call last):
  File "/home/kali/Desktop/test1.py", line 12, in <module>
    image = Image(sys.argv[1])
IndexError: list index out of range
python image arguments command line
1个回答
0
投票

试试看它的工作原理:

导入系统 导入 imghdr 从 exif 导入图像

if name == "main": 尝试: # 检查是否指定了图像文件 如果 len(sys.argv) < 2: raise FileNotFoundError('No image file has been specified!')

    # check if the specified file is an image file
    if imghdr.what(sys.argv[1]) is None:
        raise ValueError('The specified file is not an image file!')

    # load the image and print the EXIF data
    image = Image(sys.argv[1])
    print("Source File: " + str(sys.argv[1]))
    print("Make: " + image.make)
    print("Model: " + image.model)
    print("Original Date/Time: " + image.datetime)
    print(image.gps_latitude)
    print(image.gps_longitude)

except FileNotFoundError:
    print('No image file has been specified!')
except ValueError:
    print('The specified file is not an image file!')
© www.soinside.com 2019 - 2024. All rights reserved.