Jon Cage
Jon Cage

Reputation: 37488

Why does argparse fail to recognise an argument when a Python script is called directly?

I have a simple script like this (based on the docs for argparse):

def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("issuenumber", help="Create a local branch based on the specified issue number", type=int)
    args = parser.parse_args()

    if args.issuenumber:
        print("Starting work on issue #"+str(args.issuenumber))

if __name__ == "__main__":
    Main()

When I run it however, it never recognises the argument I'm passing it:

C:\Projects\PyTools>Gritter.py 1
usage: Gritter.py [-h] issuenumber
Gritter.py: error: the following arguments are required: issuenumber

If I call the script via a python call it works however:

C:\Projects\PyTools>python Gritter.py 1
Starting work on issue #1

If I print out sys.argv I get:

C:\Projects\PyTools>Gritter 1
['C:\\Projects\\PyTools\\Gritter.py']

C:\Projects\PyTools>Python Gritter.py 1
['Gritter.py', '1']

So I guess something is not passing on the arguments when the script is called directly. I wonder if there's anything that can be done so that the script can be called directly?

Upvotes: 2

Views: 300

Answers (2)

Jon Cage
Jon Cage

Reputation: 37488

Based on mckoss` answer, I modified the following registry key:

HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command

From this:

"C:\Python34\python.exe" "%1"

To this:

"C:\Python34\python.exe" "%1" %*

And now my script works as I'd previously expected.

Upvotes: 0

hpaulj
hpaulj

Reputation: 231385

The C\ indicates you are using Windows. You have take extra effort to ensure that this 'direct call' passes arguments through to python.

Looking up windows shebang I find, from Python docs that you need to use

#!/usr/bin/python -v

to pass arguments

See https://docs.python.org/3/using/windows.html

argparse uses sys.argv. If that only has the script name then the call isn't passing arguments.

Upvotes: 1

Related Questions