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

Windows系统命令行如何通过-f/-o参数为Python脚本指定输入输出文件

实现方法(用Python标准库argparse)

这是Python官方内置的命令行参数解析库,无需额外安装第三方依赖,完全匹配你的需求,可直接运行的代码示例如下:

import argparse

def main():
    # 初始化参数解析器
    parser = argparse.ArgumentParser(description="文件处理示例脚本")
    # 添加-f参数,对应输入文件
    parser.add_argument('-f', '--input-file', help='指定读取的输入文件路径', required=False)
    # 添加-o参数,对应输出文件
    parser.add_argument('-o', '--output-file', help='指定写入的输出文件路径', required=False)
    
    # 解析传入的命令行参数
    args = parser.parse_args()
    
    # 业务逻辑示例
    if args.input_file:
        print(f"已获取输入文件路径:{args.input_file}")
        # 此处补充读文件逻辑,例如:
        # with open(args.input_file, 'r', encoding='utf-8') as f:
        #     content = f.read()
    if args.output_file:
        print(f"已获取输出文件路径:{args.output_file}")
        # 此处补充写文件逻辑,例如:
        # with open(args.output_file, 'w', encoding='utf-8') as f:
        #     f.write("待写入内容")

if __name__ == "__main__":
    main()

使用说明

  • 执行python main_file.py -f input1.txt时,程序会自动获取input_file参数值为input1.txt
  • 执行python main_file.py -o output1.txt时,程序会自动获取output_file参数值为output1.txt
  • 两个参数支持同时传入:python main_file.py -f input1.txt -o output1.txt
  • 如果你需要让某个参数为必填项,把add_argument中的required参数改为True即可
  • 执行python main_file.py -h可以自动生成帮助提示,无需手动编写说明内容

可选方案:用sys.argv手动解析(不推荐)

如果你不想用argparse,也可以直接读取sys.argv列表手动解析参数,示例如下:

import sys

if __name__ == "__main__":
    arg_list = sys.argv
    input_file = None
    output_file = None
    for index in range(len(arg_list)):
        if arg_list[index] == '-f' and index + 1 < len(arg_list):
            input_file = arg_list[index + 1]
        if arg_list[index] == '-o' and index + 1 < len(arg_list):
            output_file = arg_list[index + 1]
    
    if input_file:
        print(f"输入文件:{input_file}")
    if output_file:
        print(f"输出文件:{output_file}")

该方案需要自己处理参数缺省、异常报错、帮助提示等逻辑,维护成本高,优先选择argparse方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:15:00