Gughan Ravikumar Gughan Ravikumar - 1 year ago 77
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

and I tried running this script from there.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()

If I run

>python 1

in the command line, I get the expected result

But if I run

> 1

I get

usage: [-h] [--sum] N [N ...] 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download