You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何使用getopt接收字符串输入,为反向图搜脚本传入文件路径

使用getopt模块改造反向图片搜索脚本实现路径参数传入

getopt模块解析参数时,带值参数的标识为短选项后加:、长选项后加=,解析得到的参数值默认就是字符串类型,无需额外转换,完全适配文件路径这类字符串入参的需求。

首先需要补充导入依赖:除了原有的requests,还需要导入sys(用于获取命令行参数)、getopt(用于解析参数)、json(原脚本遗漏的依赖,用于解析接口返回结果)。

改造后的完整代码如下:

import sys
import getopt
import json
import requests

def main():
    filePath = ""
    # 定义参数规则:短选项f需要传值,长选项file-path需要传值
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help", "file-path="])
    except getopt.GetoptError:
        # 参数错误时提示用法
        print('用法:reverse_search.py -f <图片文件路径>')
        print('或:reverse_search.py --file-path <图片文件路径>')
        sys.exit(2)
    # 遍历解析得到的参数
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print('用法:reverse_search.py -f <图片文件路径>')
            print('或:reverse_search.py --file-path <图片文件路径>')
            sys.exit()
        elif opt in ("-f", "--file-path"):
            filePath = arg
    # 校验路径是否传入
    if not filePath:
        print("错误:未传入图片文件路径")
        print('用法:reverse_search.py -f <图片文件路径>')
        sys.exit(2)
    
    # 原搜索逻辑保持不变,替换硬编码路径即可
    searchUrl = 'https://yandex.ru/images/search'
    files = {'upfile': ('blob', open(filePath, 'rb'), 'image/jpeg')}
    params = {'rpt': 'imageview', 'format': 'json', 'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
    response = requests.post(searchUrl, params=params, files=files)
    query_string = json.loads(response.content)['blocks'][0]['params']['url']
    img_search_url= searchUrl + '?' + query_string
    print(img_search_url)

if __name__ == "__main__":
    main()

使用方式

  • 短参数调用:python reverse_search.py -f "C:\path\test.jpg"
  • 长参数调用:python reverse_search.py --file-path "C:\path\test.jpg"
    注意:如果文件路径包含空格,需要用引号把路径整体包裹起来

内容的提问来源于stack exchange,提问作者user14768474

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:15:08