[Tutor] Shebang (#!) in the first line of a python script

Dave Angel davea at ieee.org
Tue Oct 13 12:24:42 CEST 2009


Alan Gauld wrote:
> "Katt" <the_only_katala at verizon.net> wrote
>
>> Okay.  So if I were to place the following in my Windows XP py v.2.6.2 :
>>
>> $ (name of python script)
>>
>> Then as long as python was in my path I would be able to type the 
>> name of the script like a Dos batch file (ex: lowertoupper.py or 
>> lowertoupper) instead of having to type python lowertoupper.py?  And 
>> it will run as normal?
>
> The shebang line does nothing on Windows, it is just a comment.
> Windows uses the file extension so, provided you end the file in .py,
> you can just type in the name of the script and Windows will use the
> file association to find the interpreter.
>
> This is a somewhat fragile mechanism and if you have two versions
> of Python installed or the associations get broken it may fail but most
> of the time it works fine.
>
As Alan says, the default shells in Windows ignore the shebang line.  So 
unless you have a custom shell installed, you need to understand the 
Windows pattern.

They have another mechanism, which involves two registry entries and an 
environment variable.  The registry entries can easily be manipulated 
using the utility programs assoc.exe and ftype.exe.  However, as long as 
you have a single Python installation, these are probably already setup 
for you.  If you have more than one Python version installed, you might 
need to use ftype to switch which one is your default.

As long as you're using this mechanism, python.exe does *not* have to be 
on your PATH.  The full path location of python.exe is set up by ftype.  
You may want your script(s) to be on your PATH of course.

The environment variable is used to avoid the need to type the 
extension.  This is *not* set up by default in the Python installation, 
at least in my experience.  But you can easily do it yourself.  The 
environment variable PATHEXT has a list of extensions that it will 
search for.

Mine looks like:
   PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW

Yours probably doesn't yet have the last two entries, and the others 
might be somewhat different as well.

With .py in this variable, you can type lowertoupper  instead of 
lowertoupper.py

DaveA



More information about the Tutor mailing list