16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 17 ■ EXTENDING PYTHON 359<br />

Once you have compiled the class (and put the .class file either in your current direc<strong>to</strong>ry<br />

or somewhere in your Java CLASSPATH), you can fire up Jython (with the jython command) and<br />

import the class directly:<br />

>>> import JythonTest<br />

>>> test = JythonTest()<br />

>>> test.greeting()<br />

Hello, world!<br />

See? There’s nothing <strong>to</strong> it.<br />

■Tip If you’re working with Java, you can also use the command jythonc <strong>to</strong> compile your <strong>Python</strong> classes<br />

in<strong>to</strong> Java classes, which can then be imported in<strong>to</strong> your Java programs.<br />

Listing 17-2 shows a similar class in C#. Compile this with your compiler of choice (free<br />

software available from http://www.mono-project.com).<br />

Listing 17-2. A Simple C# Class (Iron<strong>Python</strong>Test.cs)<br />

using System;<br />

namespace FePyTest {<br />

public class Iron<strong>Python</strong>Test {<br />

public void greeting() {<br />

Console.WriteLine("Hello, world!");<br />

}<br />

}<br />

}<br />

One way of using this in Iron<strong>Python</strong> would be <strong>to</strong> compile the class <strong>to</strong> a DLL (see the documentation<br />

for your C# installation for details) and update the relevant environment variables<br />

(such as PATH) as needed. Then you should be able <strong>to</strong> use it as in the following (using the<br />

FePyConsole prompt):<br />

>>> import sys<br />

>>> sys.LoadAssembly<strong>From</strong>File("Iron<strong>Python</strong>Test.dll")<br />

>>> import FePyTest<br />

>>> f = FePyTest.Iron<strong>Python</strong>Test()<br />

>>> f.greeting()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!