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

Python argparse使用问题:命令行传入路径后参数无法识别报错

Fixing the argparse Error in Your File Search Script

Hey there! Let's break down why you're getting that "unrecognized arguments" error and fix your script step by step.

What's Causing the Error?

Your error message tells us that argparse doesn't recognize the ../seek path you're passing. This usually happens for one of two reasons:

  • You didn't define a positional argument for the directory path in your argparse setup (maybe you used an optional --path flag but forgot to include it in your command).
  • Your -name flag is configured as a boolean (on/off) option instead of one that accepts a regex value, so argparse thinks the [a-z]*\.txt part is an unknown argument.

Correct Argparse Setup

Here's a working version of your script that addresses both issues:

import argparse
import os
import re

def find_matching_files(directory, regex_pattern):
    # Compile the regex for efficiency
    pattern = re.compile(regex_pattern)
    # Walk through the directory and subdirectories
    for root, _, filenames in os.walk(directory):
        for filename in filenames:
            if pattern.match(filename):
                print(os.path.join(root, filename))

if __name__ == "__main__":
    # Set up the argument parser
    parser = argparse.ArgumentParser(description="Search for files matching a regex in a directory")
    
    # Add positional argument for the directory path (required)
    parser.add_argument("path", help="Directory to search through")
    
    # Add -name flag that accepts a regex value (required)
    parser.add_argument("-name", required=True, help="Regex pattern to match filenames")
    
    # Parse the command line arguments
    args = parser.parse_args()
    
    # Run the search function
    find_matching_files(args.path, args.name)

How to Use the Script

Run your command exactly as you tried before (the quotes are critical to prevent your shell from expanding the regex before it reaches Python):

./find.py ../seek -name '[a-z]*\.txt'

Key Fixes Explained

  • Positional path argument: This tells argparse to expect the directory path as the first input, no flag needed.
  • -name with a value: By omitting action='store_true', argparse knows -name needs to be followed by your regex pattern.
  • Quoting the regex: The single quotes around [a-z]*\.txt stop your shell from trying to expand the wildcard before passing it to your script—this ensures the regex is handled by Python's re library instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:27:40