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

如何通过argparse接收--id参数并将其作为变量复用?

问题排查与修复方案

代码存在的核心问题:

  • 重复解析命令行参数:连续两次调用parser.parse_args(),第一次用vars()转成字典后被第二次的命名空间覆盖,属于冗余代码。
  • 未正确获取传入的ID参数:main函数中使用了未定义的hardware_id_input变量,完全没从解析后的参数中提取--id的值。
  • 未执行核心逻辑:仅定义了main函数但没有调用,导致程序不会运行任何功能代码。
  • 拼写小问题:description里的hardare应为hardware,不影响功能但建议修正。

修复后的代码:

import argparse

# 假设get_host_information是你已经实现的函数
def get_host_information(hardware_id):
    # 这里示例返回模拟数据,实际替换成你的业务逻辑
    return {"hostname": "test-host-01", "hardware_id": hardware_id}

parser = argparse.ArgumentParser(description='Return a list of useful information after specifying a hardware/asset ID')
parser.add_argument('--id', type=str, required=True, help='A hardware/asset id to provide information on')
args = parser.parse_args()

def main():
    hardware_id = args.id
    host = get_host_information(hardware_id)
    print(host["hostname"])
    print(host["hardware_id"])

# 调用main函数执行逻辑
if __name__ == "__main__":
    main()

用法说明:

现在可以通过以下形式运行程序:

python your_script.py --id 123456

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:45:38