Working with Hosting APIs
❘
297
You may wonder why Figure 14-3 shows so many assemblies selected when the
example code only uses one of them directly. The other assemblies are dependen-
cies that the assemblies you use directly require to execute. The code will compile
just fine without these other assemblies, but the application will raise an exception
when you try to execute it. If you run into a situation where you think that the
application should execute, but it keeps raising an exception, read the exception
information carefully to determine whether a missing assembly is the problem.
LISTINg 14-2:
Executing the IronPython script
static void Main(string[] args)
{
// Create an IronPython ScriptRuntime.
ScriptRuntime Runtime = IronPython.Hosting.Python.CreateRuntime();
// Execute the script file and return scope information about
// the task.
ScriptScope Scope = Runtime.ExecuteFile(“Test.py”);
// Display the name of the file executed.
Console.WriteLine(“\r\nExecuted {0}“,
Scope.GetVariable(“__name__“));
// Keep the output visible.
Console.WriteLine(“\r\nPress any key...”);
Console.ReadLine();
}
The code begins by creating the
ScriptRuntime
object,
Runtime
. Notice that you create this object
by directly accessing the IronPython assemblies, rather than the DLR assemblies. There are many
ways to accomplish this task, but using the technique shown is the simplest. The
Runtime
object
contains default settings for everything. For example, this
ScriptRuntime
doesn’t provide debug-
ging capability. Consequently, this technique is only useful when you have a debugged script to work
with and may not do everything needed in a production environment where you let users execute
their own scripts as part of an application.
The
Runtime.ExecuteFile()
method is just one of several ways to execute a script. You use it
when a script appears in a file on disk, as is the case for this example. When you call the
Runtime
.ExecuteFile()
method, your application actually calls on the IronPython interpreter to execute
the code. The output from the script appears in Figure 14-4. As you can see, the code executes as you
expect without any interference from the host. In fact, you can’t even tell that the application has a host.
FIgURE 14-4:
The script output appears as you might expect.
548592c14.indd 297
2/24/10 12:49:07 PM
www.finebook.ir
Do'stlaringiz bilan baham: |