PySh - Writing Scripts

All you've got to do is write a simple Python class that adheres to a basic interface, and PySh does the rest.

Here's the interface that PySh requires for your Python classes:

class Example:
    description = "Description...";

    def Exec( self, dte ):
        pass;
    
  • The description attribute reference (or static variable in C++) is the name Visual Studio will use if this command is bound to a button, or the text it will display when a user hovers the mouse pointer over any control bound to the command.
  • The Exec method is called by PySh whenver Visual Studio attempts to execute the class. The dte argument is a reference to the top-level object in the Visual Studio automation object model (see _DTE in MSDN for details). We use this object to manipulate Visual Studio.

Here's a real example of a command that flips between .cpp and .h files:

import pysh;

# Microsoft Development Environment 8.0
pysh.MakeAlias(
    "_dte",
    "{80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2}",
    8, 0, 1 );

import _dte;

class HeaderFlip:
    description = "Flip between .cpp & .h files";

    def Exec( self, dte ):
        doc = dte.ActiveDocument;
        if( not doc ):
            return;

        path = os.path.splitext( doc.FullName );
        flipPath = str( path[ 0 ] ).lower();
        
        if( path[ 1 ] == '.cpp' ):
            flipPath += '.h';
        elif( path[ 1 ] == '.h' ):
            flipPath += '.cpp';
        else:
            return;

        dte.ItemOperations.OpenFile( 
            flipPath, _dte.constants.vsViewKindAny );
    
  • The pysh.MakeAlias is a wrapper around Python COMs makepy. In this example, we're makepy'ing the Visual Studio 2005 (Version 8.0) type library and then aliasing that module to _dte. Then we import the _dte module.
  • We retrieve the active document (if any) from Visual Studio
  • Check the documents path, and check its extension. If it's .cpp or .h, we flip the extension
  • Try and open the file at the flipped path

This example, and others just like it, can be found in <installdir>\examples.py

See also

Python Shell for Visual Studio is completely free, but if you want to contribute towards the running costs of this website, then please click on the button on the right and donate via PayPal