James Cagalawan
James Cagalawan

Reputation: 3

Can't pass zero arguments to Python program running on Windows command line

When I run the following file directly through the command line

# winargs.py
import sys
print(sys.argv)

by placing that file in a directory in PATH and running the command winargs.py in either Window Command Prompt or Powershell, I get an unexpected trailing empty string.

['winargs.py', '']

I would expect it to output only the script name like so:

['winargs.py']

Windows Configuration

I previously could not pass arguments at all before but I followed the instructions here to add a "%*" to the HKEY_CLASSES_ROOT\Python.File\shell\open\command registry key and I can now pass arguments so running winargs.py a b 1 2 outputs ['winargs.py', 'a', 'b', '1', '2']. I am using the Anaconda distribution of Python for Windows and had that Python set as my Default Program for running *.py files. The registry key I modified after setting the default is

[HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command]
"C:\Users\Me\Anaconda3\python.exe"  "%1" "%*"

Larger Problem with argparse

This is causing larger difficulties when running scripts written with argparse that only have required positional arguments. Instead of printing a help message, it interprets that empty string as the first positional argument. For example, for the program

# winargparse.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("first_arg")
parser.parse_args()

I see no output running the command winargparse.py from both the Command Prompt and PowerShell, but expect it to print the default argparse help message as it does when I run python winargparse.py which looks like

usage: winargparse.py [-h] first_arg
winargparse.py: error: the following arguments are required: first_arg

How can I get Windows Command Prompt to run my Python files both without arguments and with arguments?

Upvotes: 0

Views: 606

Answers (1)

Alexander Ushakov
Alexander Ushakov

Reputation: 5399

You have unneeded double quotes around %* in your registry record. They make Windows pass an empty parameter if there are no arguments. Just remove these quotes.

Upvotes: 2

Related Questions