次の方法で共有


Getting Started with IronPython

I recently spent some time getting IronPython up and running on my system; I will review what I learned in this post.

Hosted inside an interpreter, Python belongs to the same family of scripting tools as VBScript, JavaScript, Perl and Ruby. You can fairly compare Python to a general purpose language such as C#. Developers praise this loosely typed, dynamic language for its ease of use and rapid development capabilities. IronPython is Microsoft’s free version of the open source Python language.

IronPython can be hosted inside a C# program as a scripting language. Nonetheless, Python is a powerful standalone language frequently used as the glue in web based applications. Before I came to work for Microsoft I enjoyed using it as part of my daily toolkit.

In this post I explore the simple steps needed to run IronPython as a standalone tool from the command prompt. In other posts I will show how to call Python from inside a C# application.

Installing Python

I started by downloading IronPython from CodePlex and installing it. The whole process from first visit to the IronPython web site until IronPython was installed probably took me little more than a minute. Below are the links to retrieve the code. If you are reading this article in 2009 or early 2010, consider using the first link, if the date is later than that then use the second link and look for a newer release:

Download the IronPython MSI Windows install file, then double click on it to run setup. When you are done, your IronPython installation will probably be located in a directory similar to this one:

  • C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2

Once you have the IronPython interpreter installed, you need to follow these steps to run a sample program:

  1. Put IronPython on your Path
  2. Create an IronPython program
  3. Compile and run the program.

In the next few sections of this post I’ll walk you through these steps. When you are done, you will have IronPython up and running on your system.

Setting Up Your Path

You can run IronPython from inside Visual Studio, but the tools for doing so are still primitive. Most Python developers work inside a lightweight editor and run Python from inside the IronPython interpreter or from the command line. This post focuses on building Python from the command line. To get started with that process, you will probably want to begin by ensuring that the IronPython interpreter is on your System Path.

They say there must be fifty ways to set the system path. In this post I will outline two of them as practiced by developers on Vista or Windows 7. In both cases you can begin with a four step process to bring up the Environment Variables Dialog:

  • Method One
    • Press the Windows Key to bring up the Start Menu
    • Right click on Computer and choose Properties
    • Click Advanced Computer Settings
    • Click Environment
  • Method Two
    • Press the Windows Key to ring up the Start Menu
    • Type Control Panel and press enter
    • You should be taken automatically to the search box on the top right of the control panel, if not, press Ctrl-E to get there and type Environment. (The first three letters should be all that’s necessary)
    • Hit tab twice to select Edit Environment Variables, and then hit enter.

Which ever technique you use, the dialog shown in Figure 1 should appear. You can use this dialog to edit the system path.

Figure01

Figure 1: In this screenshot, a variable called Path has been added to the list of User Variables. It lists the path to the IronPython Interpreter.

Once the dialog appears, click New (Alt-N) to add a Path variable for your account. A small dialog appears. Paste the path to IronPython into this dialog and click the OK button. The path should be similar to the path shown above which points to the directory where IronPython was installed. Click OK to close the Environment Variables dialog. From now on, and Command prompt window that you open should have an environment automatically set up to point to the IronPython interpreter. To test that everything is working correctly, go to the command prompt and type ipy. If everything has gone well, you should see a result like the following.

 C:\Users\Charlie\Documents\Python\PythonPost>ipy
IronPython 2.6 (2.6.10920.0) on .NET 4.0.21006.1
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

As shown above, you can type exit() and then enter to quit the interpreter. You can also execute Python code from inside the interpreter. Working interactively inside the interpreter is a useful and powerful way to write code, but I will not cover it in this post.

Create a Python Program

Now that you have Python on your path, you can easily compile your projects from the command line. Depending on your tastes, you can edit your program in Visual Studio, in NotePad, or in NotePad++. The goal is to create a simple text-based source file with the letters py as an extension. Here, for example, is the complete contents of a simple Python source file:

 print "Very Simple Test"

You can save this source file as VerySimpleTest.py, and process and run it by passing its name to the Python interpreter. The interpreter will process and run the program:

 C:\Users\Charlie\Documents\Python\PythonPost>ipy VerySmipleTest.py.
Very Simple Test

Now that you understand the basics, the next step is to understand how to create functions, classes and multiple module projects.

Python uses indentation rather than keywords or syntax to define blocks of code. Here, for instance, is how to define a function in Python:

 def WriteTest():
  print "This is a test"

The keyword def followed by a name and a colon defines the header for the function. The next line begins with tab character. This defines the beginning of main block for the function, which in this case contains a single line of code. If you had multiple lines in the function, then you would indent each line with a tab character. An empty line defines the end of the function.

To define a class, you repeat the same process, but use the keyword class rather than def:

 class SimpleLocalClass:
   def SimpleMethod(self):
     print "Simple Local Class"

Here you see the definition for a class called SimpleLocalClass which has a single method called SimpleMethod. Not everyone likes the Python syntax for defining classes and methods, but I have found intuitive and easy to use.

Listings 1 and 2 contain a project with two files that demonstrates how to use functions and classes in Python:

Listing 1: Here is the main module for the project. It is a simple source file called Project.py containing a function and a simple class. This source file also has a dependency on a class called SimpleClassTest that is shown in Listing 2

 from SimpleClass import SimpleClassTest

class SimpleLocalClass:
    def SimpleMethod(self):
     print "Simple Local Class"

def WriteTest():
    print "This is a test"
    
WriteTest()

simpleLocalClass = SimpleLocalClass()
simpleLocalClass.SimpleMethod()

simpleClass = SimpleClassTest()
simpleClass.SimpleMethod()    

Listing 2: The second file in this project is called SimpleClass.py . The file shown in Listing 1 depends on this class.

 class SimpleClassTest:
    def SimpleMethod(self):
     print "Simple Class"

Notice the from statement at the top of Listing 1. It is used to import the class found in Listing 2. I should also point out that there is no main() method shown in listing 1. The word main does not have the same significance in Python that it does in C#. The entry point for this Python program is the last set of un-indented statements found in Project.py . In this case the entry point begins with the call to WriteTest().

Compiling and Running the Program

Now that you have the two source files for your project, all you need do is compile and run them. The Python interpreter is designed to make this task as simple as possible. You need only reference the primary file for your project, the interpreter is smart enough to to parse the from import statement at the top of Listing 1 and figure out from that how to include SimpleClass.py in the project.

Listing 3: Here is the command to process and run the files shown in Listings 1 and 2. The output from the command is also shown.

 C:\Users\Charlie\Python\PythonPost>ipy Project.py
This is a test
Simple Local Class
Simple Class

Summary

In this post I have reviewed how to download and install IronPython, and how to get some simple Python scripts up and running on your system. You saw how to run a simple program from the command line, how to create:

  • A simple function
  • A simple class
  • And a mutli-module project.

In future posts I will focus on calling IronPython from a C# program.

kick it on DotNetKicks.com