Search code examples
pythonpython-3.xparameters

How to get the count of command line parameters in Python regardless of python keyword?


I have a small sample program in Python:

import sys
print ("This is the name of the script: "+ sys.argv[0])
print ("Number of arguments: " + str(len(sys.argv)))
print ("The arguments are: " + str(sys.argv))

I run it in Windows CLI:

python args.py -a -b

Output:

This is the name of the script: args.py
Number of arguments: 3
The arguments are: ['args.py', '-a', '-b']

Looks good. Now I call it without specifying "python":

args.py -a -b

Now the output is totally different:

This is the name of the script: C:\args.py
Number of arguments: 1
The arguments are: ['C:\\args.py']

Shouldn't I be getting the same result? Why does it show a different argument count, even though python.exe is executing the program in both cases?

How do I correct this?


Solution

  • Looks like there's a solution on this stackoverflow thread, reproduced below:

    I search in regedit keyword "python" and found two keys missing %* after "C:\Python27\python.exe" "%1":

    Computer\HKEY_CLASSES_ROOT\Applications\python.exe

    Computer\HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

    And .py is associated with py_auto_file even though I tried assoc .py Python.File

    Changing the two keys fixed this issue, thanks!