brian buck
brian buck

Reputation: 3454

sys.argv Contents When Calling Python Script Implicitly on Windows

I have a added .PY files to my System Environment PATHEXT variable on Windows 7. I have also added C:\scripts to my PATH variable.

Consider I have a very simple Python file C:\Scripts\helloscript.py

print "hello"

Now I can call Python scripts from my Console using:

C:\>helloscript

And the output is:

hello

If I change the script to be more dynamic, say take a first name as a second parameter on the Console and print it out along with the salutation:

import sys
print "hello,", sys.argv[1]

The output is:

c:\>helloscript brian
Traceback (most recent call last):
File "C:\Scripts\helloscript.py", line 2, in <module>
    print sys.argv[1]
IndexError: list index out of range

sys.argv looks like:

['C:\\Scripts\\helloscript.py']

If I call the script explicitly the way I would normally:

C:\>python C:\Scripts\helloscript.py brian

The output is:

hello, brian

If I try to use optparse the result is similar although I can avoid getting an error:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--firstname", action="store", type="string", dest="firstname")
(options, args) = parser.parse_args()
print "hello,", options.firstname

The output is:

hello, None

Again, the script works fine if I call it explicitly.


Here's the question. What's going on? Why doesn't sys.argv get populated with more than just the script name when calling my script implicitly?

Upvotes: 2

Views: 1362

Answers (1)

brian buck
brian buck

Reputation: 3454

It turns out I had to manually edit the registry:

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

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

And should have been:

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

Upvotes: 4

Related Questions