Wednesday, December 25, 2002

Add .py and .pyw to PATHEXT on Windows

Happy holidays everyone!

While reading the following cookbook entry I realized many people probably don't know there is an easier way to invoke Python scripts just like batch files and other executables on your PATH under Windows. I went ahead and added a comment to the cookbook and I've included the description below and some additional details.

There is a much simpler way than wrapping a Python script in a batch file. Simply add .py and .pyw to the PATHEXT environment variable on Windows NT, 2000, and XP (possibly Win9x and ME too, but I can't test that).

Open the System Control Panel, select the Advanced tab and then click the Environment Variables... button to bring up the dialog. PATHEXT is listed under the System variables. Once you've made the change, if you type set and press return in the command shell you should see your change:


Now if you have a program called in one of the directories on your PATH, you can invoke it by just typing hello and return. Here's a simple test script showing that you do get command-line args as well.

import sys
print "hello", sys.argv

I ran it at the command prompt (note that I stuck in my c:\posix directory which was already on my PATH).

C:\>hello world
hello ['C:\\posix\\', 'world']

Of course one of the nice things about using Python scripts instead of batch files or scripts written in VBScript and JavaScript is that the scripts are portable to Unix and other operating systems as long as you don't use any Windows-specific extensions such as COM; the Python standard libs provide a lot of functions and methods to hide platform differences such as path separators.

If you do need to access COM or manipulate the registry in your scripts, you'll want to install Mark Hammond's win32all extension. Among other things, I use win32all to manipulate the Outlook object model with Python instead of having to use VBA or VBScript.

Associating file extensions with scripts

Note that you still won't be able to select a .py or .pyw file in the Explorer to open files of a particular extension. In order to do that, you'll need to use a variation of the instructions for associating .py and .pyw files with the codeEditor found on the codeEditor wiki page:

Just substitute your program for the codeEditor, and the extensions such as .txt, or .jpg, etc. you want to open. I use this trick so that the PythonCard pictureViewer sample can open image files on my machine and the textEditor and codeEditor tools can open text files including HTML and XML; the codeEditor is particularly good for very large HTML and XML files which can cause HomeSite and other HTML editors to slowdown.

11:55:51 AM    comment []