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
--pathflag but forgot to include it in your command). - Your
-nameflag is configured as a boolean (on/off) option instead of one that accepts a regex value, so argparse thinks the[a-z]*\.txtpart 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
pathargument: This tells argparse to expect the directory path as the first input, no flag needed. -namewith a value: By omittingaction='store_true', argparse knows-nameneeds to be followed by your regex pattern.- Quoting the regex: The single quotes around
[a-z]*\.txtstop your shell from trying to expand the wildcard before passing it to your script—this ensures the regex is handled by Python'srelibrary instead.
内容的提问来源于stack exchange,提问作者ajax
相关产品推荐
相关产品推荐

