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

如何用Python从input.txt读取参数值并传入params?

从input.txt读取动态参数并传入API调用的Python实现

实现步骤

  1. 读取文件内容:读取input.txt的文本内容,去除多余的换行、空格等空白字符。
  2. 解析参数为字典:将逗号分隔的键值对字符串转换为Python字典,适配API调用所需的params格式。
  3. 传入API调用:把解析好的字典直接传入请求的params参数中完成调用。

完整代码示例

import requests

def load_params(file_path):
    try:
        with open(file_path, 'r') as f:
            content = f.read().strip()
        
        params_dict = {}
        # 拆分每个键值对,处理值中包含空格的情况
        for pair in content.split(','):
            key, val = pair.split('=', 1)  # 仅拆分第一个=,避免值内有=时出错
            params_dict[key.strip()] = val.strip()
        
        return params_dict
    except FileNotFoundError:
        print(f"错误:找不到文件 {file_path}")
        return None
    except ValueError:
        print("错误:文件格式错误,需为key=value,key=value的格式")
        return None

# 读取参数并调用API
params = load_params('input.txt')
if params:
    target_api = "https://your-api-endpoint.com"
    resp = requests.get(target_api, params=params)
    
    if resp.status_code == 200:
        print("调用成功:", resp.json())
    else:
        print(f"调用失败,状态码:{resp.status_code}")

关键说明

  • 函数load_params包含基础异常处理,避免文件缺失或格式错误导致程序崩溃。
  • 使用split('=', 1)确保参数值中包含=时也能正确解析(比如值为abc=123的场景)。
  • 解析后的字典直接传入requests.get的params参数,requests会自动转换为合法的URL查询参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:00:05