为何argparse仅在显式调用Python解释器时才能正常工作?
Let’s break down what’s happening here and why you’re seeing this behavior.
First, here’s your code example formatted for clarity:
import argparse parser = argparse.ArgumentParser() parser.add_argument('w') cmd_args = parser.parse_args() print(cmd_args.w)
When you run the script directly without invoking Python explicitly, you get an error:
C:\Users\nheme\Desktop> command_line_parse.py test_argument usage: command_line_parse.py [-h] w command_line_parse.py: error: the following arguments are required: w
But when you explicitly call the Python interpreter, it works as expected:
C:\Users\nheme\Desktop> python command_line_parse.py test_argument test_argument
The Root Cause
This issue is almost always tied to an incorrect file association setup for .py files on Windows.
When you run a .py script directly (without typing python), Windows uses the default program assigned to .py files to execute it. For the script to receive all command-line arguments, the file association must include passing all arguments to the Python interpreter. If this is missing, only the path to the script itself is passed to argparse—your test_argument never reaches the script, hence the error that the required positional argument w is missing.
How to Fix It
Let’s verify and correct your file associations:
Check the current .py file association
Open Command Prompt and run:assoc .pyYou should get output like
.py=Python.File(the exact name may vary slightly based on your Python version).Check the command linked to the file type
Next, run:ftype Python.FileThe correct output should look something like this (replace the path with your actual Python executable path):
Python.File="C:\Python39\python.exe" "%1" %*The
%*at the end is critical—it tells Windows to pass all additional command-line arguments to the Python interpreter.Fix the association if needed
If%*is missing from the command, update it with this command (adjust the path to match your Python installation):ftype Python.File="C:\Path\To\Your\python.exe" "%1" %*
Why Explicit Invocation Works
When you run python command_line_parse.py test_argument, you’re directly instructing the Python interpreter to execute the script and pass all subsequent arguments to it. This bypasses the Windows file association layer entirely, so all arguments are correctly received by argparse.
内容的提问来源于stack exchange,提问作者Nick-H

