File extension

Steve Holden steve at holdenweb.com
Sat Mar 17 11:29:43 CET 2007


Anil Kumar wrote:
> Hi,
>  
> Can Python Script can have different extensions like .sh etc.... Or Is 
> .py is mandatory to be present as the extension for the Python Script.
>  
The interpreter itself doesn't really care. The issues you are hotting 
are due to operating system. and command shell differences.

> We have an application where the script was initially written in shell 
> script with extension .sh. Now we are migrating this script to be run in 
> both Unix and Windows, so using Python for migration.
>  
Good for you!

> I have created a new Python Script porting all the changes in shell 
> script and it is working fine in Unix/Linux operating system. Later I 
> changed the extension of the file from .py to .sh, even then it worked.
>  
The Unix command interpretation mechanism uses PATH as a list of 
directories to search for the named command file (the first word of the 
expanded command line). It then looks for the magic string "#!" at the 
start of the executable file and, if it finds that string, it passes the 
file to the interpreter named in the rest of the line for execution as a 
program.

Your Python files probably begin with something like

#!/usr/bin/python

or

#!/usr/bin/env python

> But when I try a python script with extension .sh in windows, the file 
> is not getting recognized by the Python interpreter. Is this supported? 
> Or is there any way we can achieve the same?
>  
In Windows, alas, the mechanism is less versatile. The command 
interpreter uses an environment variable called PATHEXT to decide which 
extensions to check when it sees a command that it can't find directly. 
For example, my PATHEXT variable is currently

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

(you'll observe I have given up on the PATHEXT mechanism - it's too much 
of a pain in the butt for me, so I just code explicit calls to the 
python interpreter).

It looks on the PATH for a file with the given name and each extension, 
and when it finds one it then runs the interpreter registered for that 
type of file.

> The reason I am trying to change the extension is, it reduces lot of 
> porting changes. No need to go to each of our file which were 
> referencing .sh file before and change it to .py.
>  
> Any Help would be greatly Appreciated.
>  
You could cheat ... if you register the .SH extension as "to be handled 
by the python interpreter" and then add .SH to PATHEXT this should work 
under Windows.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com
See you at PyCon?         http://us.pycon.org/TX2007




More information about the Python-list mailing list