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

命令行可指定路径,直接运行elis_client_example.py提示文件路径未定义

解决直接运行脚本时"document path is not defined"的问题

这个错误的根源很清晰:你的脚本依赖argparse模块从命令行参数中获取文档路径和API密钥,但当你直接在Python环境(比如IDE、IDLE)中运行脚本时,没有传入这些必要参数,导致argparse无法解析出必填的document_path,从而抛出错误。

下面提供两种实用的解决方案:

方案一:在IDE中配置运行参数

如果你习惯用IDE直接运行脚本,可以在运行配置里手动添加命令行参数,模拟终端运行的方式:

  • 以PyCharm为例:打开Run > Edit Configurations,在Parameters输入框中填入类似内容:
    input.pdf -s "你的认证密钥"
    
  • 其他IDE(比如VS Code)也有类似的运行参数配置项,填入对应的参数即可正常执行。

方案二:修改脚本,支持交互输入参数

如果你希望脚本在没有命令行参数时自动提示用户输入必要信息,可以修改main()函数,捕获argparse的退出异常,切换到交互模式运行。

修改后的完整代码如下:

from __future__ import division, print_function
import argparse
import json
import os
import csv
import requests
import polling

DEFAULT_API_URL='https://all.rir.rossum.ai/'

class ElisClient(object):
    def __init__(self, secret_key, url=DEFAULT_API_URL):
        self.secret_key = secret_key
        self.url = url
        # we do not use requests.auth.HTTPBasicAuth
        self.headers = {'Authorization': 'secret_key ' + self.secret_key}

    def send_document(self, document_path):
        with open(document_path, 'rb') as f:
            content_type = self._content_type(document_path)
            response = requests.post(
                self.url + '/document',
                files={'file': (os.path.basename(document_path), f, content_type)},
                headers=self.headers)
            return json.loads(response.text)

    @staticmethod
    def _content_type(document_path):
        return 'image/png' if document_path.lower().endswith('.png') else 'application/pdf'

    def get_document_status(self, document_id):
        response = requests.get(self.url + '/document/' + document_id, headers=self.headers)
        response_json = json.loads(response.text)
        if response_json['status'] != 'ready':
            response_json = response_json
        #print(response_json)
        return response_json

    def get_document(self, document_id, max_retries=30, sleep_secs=5):
        """ Waits for document via polling. """
        def is_done(response_json):
            return response_json['status'] != 'processing'
        return polling.poll(
            lambda: self.get_document_status(document_id),
            check_success=is_done,
            step=sleep_secs,
            timeout=int(round(max_retries * sleep_secs)))

def parse_args():
    parser = argparse.ArgumentParser(description='Elis API client example.')
    parser.add_argument('document_path', metavar='DOCUMENT_PATH', help='Document path (PDF/PNG)')
    parser.add_argument('-s', '--secret-key', required=True, help='Secret API key')  # 强制命令行运行时必须传密钥
    parser.add_argument('-u', '--base-url', default=DEFAULT_API_URL, help='Base API URL')
    return parser.parse_args()

def main():
    try:
        # 优先尝试解析命令行参数
        args = parse_args()
    except SystemExit:
        # 参数解析失败(比如直接运行脚本没传参数),切换到交互输入模式
        print("未检测到命令行参数,请手动输入必要信息:")
        document_path = input("文档路径(PDF/PNG):").strip()
        secret_key = input("API密钥:").strip()
        base_url = input(f"API基础URL(默认:{DEFAULT_API_URL}):").strip() or DEFAULT_API_URL
        
        # 创建模拟args的对象,兼容原有逻辑
        class Args:
            pass
        args = Args()
        args.document_path = document_path
        args.secret_key = secret_key
        args.base_url = base_url

    client = ElisClient(args.secret_key, args.base_url)
    #print('Submitting document:', args.document_path)
    send_result = client.send_document(args.document_path)
    document_id = send_result['id']
    #print('Document id:', document_id)
    extracted_document = client.get_document(document_id)
    #print('Extracted data:')
    #Extracted_data =(json.dumps(extracted_document, indent=4))
    #print(json.dumps(extracted_document, indent=4))
    with open('jfile.json', 'w') as jsonfile:
        json.dump(extracted_document, jsonfile, sort_keys = True, indent = 4,ensure_ascii = False)

if __name__ == '__main__':
    main()

修改说明:

  1. 在parse_args()中给--secret-key添加了required=True,确保命令行运行时必须传入密钥,避免遗漏参数导致的额外错误。
  2. 在main()中添加了异常捕获逻辑:当argparse因为缺少参数退出时,自动提示用户输入必要信息,然后模拟出args对象继续执行原有逻辑。

这样修改后,无论是通过命令行带参数运行,还是直接在Python环境中启动脚本,都能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:39:56