Gughan Ravikumar - 1 year ago 67
Python Question

# Command-line arguments dropped when running python file directly on Windows

I'm learning to include command line parameters in my code. I've read the docs for

argparse
and I tried running this script from there.

#argparse_trial.py

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
help='an integer for the accumulator')
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))


If I run

>python argparse_trial.py 1


in the command line, I get the expected result
1

But if I run

>argparse_trial.py 1


I get

usage: arg_parse_trial.py [-h] [--sum] N [N ...]
argparse_trial.py: error: the following arguments are required: N


I checked and the only argument the code seems to receive in the second case is the filename itself, no matter how many arguments are given.

I'm on a Windows machine and python is in my path.

Why is the second case failing in this script? How can I get it to work?

This is a guess, I cannot test right now, but I believe this is what is happening:

1. you type the name of your python file.
2. Windows fails to run the file as a program, so…
3. Windows tries to open the file, using the associated program (kindof with using start).
4. While doing so, it simply ignores other things on the line, and…
5. …generates a basic command line for the python interpreter to use, featuring just the interpreter itself and the target file to open.

Think of what happens when you "run" a text document.

If the command line is not generated correctly, running this command should fix it (replace the path as appropriate):

ftype Python.File=C:\Path\to\python.exe "%1" %*


Notice the %* at the end. If it's amiss, arguments will be dropped.