1. Tutorial [Introdutório]: Criando
Pluging IronPython para c#
Por: Eduardo dos Santos Pereira
Dr. em Astrofísica
pereira.somoza@gmail.com
2. Tutorial [Introdutório]: Criando
Pluging IronPython para c#
Instituto Nacional de Pesquisas Espaciais/DEA
Apresentado uma breve introdução de como
rodar um script IronPython dentro do C#, isso
permitiria a criação de plugins em IronPython
para projetos que originalmente forma escritos
em c#.
3. Materiais
Nesse Tutorial é usado o IronPython 2.7, sendo
que esse pode ser baixado no site
www.ironpyton.net
.Net 4.0
Também será usado o Visual Studio 2010
Express. É necessário o C# Visual Studio 2010
ou superior pelo fato de que as versões
anteriores não são compatíveis com o .Net 4.0
4. Passo 1
O primeiro passo será o de criar uma nova
solução no Visual Studio. Aqui será criado um
novo aplicativo do Windows, ao estilo
formulário.
6. Passo 2: Abrindo o Formulário
Agora será adicionado um Botão no
Formulário.
Após a adição do botão, com um duplo clique
no formulário será adicionado ao projeto o
arquivo Form1.cs
Nesse arquivo será acrescentada a chamada
do script
10. Passo 3: Adicionando referências
Agora é preciso adicionar as referências (.dll)
do IronPython, essas normalmente se
encontram em c:/Arquivos e
Programas/IronPython 2.7/
As dll's necessárias são:
IronPython.dll
IronPython.Modules.dll
Microsoft.Scripting.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.Metadata.dll
11. Passo 3: Adicionando referências
Essas referencias precisam ser colocadas no
diretório em que se encontra o arquivo
executável.
Isso irá permiter que o programa gerado rode
em outra máquina que não possua o
IronPython instalado
Nas Próximas figuras são mostrados esses
passos.
17. Passo 4: Programando
Agora serão acrescentadas as chamadas das
referências e criação da rotina de execução do
script.
O código final ficará como segue:
18. Passo 4: Programando
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
/*
* Extras System modules necessaries to execute
* the python script.
*/
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
/*
* Iron Python Modules and Microsoft Script engine
*/
using IronPython;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
19. Passo 4: Programando
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
Gerado pelo Visual Studio
using System.Linq;
using System.Text;
using System.Windows.Forms;
/*
* Extras System modules necessaries to execute
* the python script.
*/
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
/*
* Iron Python Modules and Microsoft Script engine
*/
using IronPython;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
20. Passo 4: Programando
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
/*
* Extras System modules necessaries to execute Usando Referências
* the python script. Importantes
*/
Do Sistema.
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
/*
* Iron Python Modules and Microsoft Script engine
*/
using IronPython;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
21. Passo 4: Programando
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
/*
* Extras System modules necessaries to execute
* the python script.
*/
using System.Collections;
using System.IO;
Chamando O IronPython
using System.Reflection; E o Microsoft.Scripting para
using System.Threading; Trabalhar
/*
* Iron Python Modules and Microsoft Script engine
*/
using IronPython;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
22. Passo 4: Programando
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*
* This button will start the python script into the new thread
*/
Thread myThread = new Thread( new ThreadStart(startPy));
myThread.Start();
}
public static void startPy()
{ /*
* This function is use to set de local directory that the
* Python script program will be executed
*/
string filename = "/Scripts/Program.py";
string path = Assembly.GetExecutingAssembly().Location;
string rootDir = Directory.GetParent(path).FullName;
RunPythonFile(rootDir, filename);
}
23. Passo 4: Programando
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{ Código Gerado
public Form1() Pelo Visual Studio
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*
* This button will start the python script into the new thread
*/
Thread myThread = new Thread( new ThreadStart(startPy));
myThread.Start();
}
public static void startPy()
{ /*
* This function is use to set de local directory that the
* Python script program will be executed
*/
string filename = "/Scripts/Program.py";
string path = Assembly.GetExecutingAssembly().Location;
string rootDir = Directory.GetParent(path).FullName;
RunPythonFile(rootDir, filename);
}
24. Passo 4: Programando
namespace WindowsFormsApplication1
{
public partial class Form1 : Form A Função que Chama
{
public Form1()
O Script será Executada
{ Como uma nova Thread
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*
* This button will start the python script into the new thread
*/
Thread myThread = new Thread( new ThreadStart(startPy));
myThread.Start();
}
public static void startPy()
{ /*
* This function is use to set de local directory that the
* Python script program will be executed
*/
string filename = "/Scripts/Program.py";
string path = Assembly.GetExecutingAssembly().Location;
string rootDir = Directory.GetParent(path).FullName;
RunPythonFile(rootDir, filename);
}
25. Passo 4: Programando
namespace WindowsFormsApplication1
{
public partial class Form1 : Form Aqui são definidas as variáveis
{ filename, que informa o
public Form1() A pastas e o script que será
{
InitializeComponent(); Executado.
} Além disso é definido o diretório
Onde está o executável.
private void button1_Click(object sender, EventArgs e)
{
/*
* This button will start the python script into the new thread
*/
Thread myThread = new Thread( new ThreadStart(startPy));
myThread.Start();
}
public static void startPy()
{ /*
* This function is use to set de local directory that the
* Python script program will be executed
*/
string filename = "/Scripts/Program.py";
string path = Assembly.GetExecutingAssembly().Location;
string rootDir = Directory.GetParent(path).FullName;
RunPythonFile(rootDir, filename);
}
26. Passo 4: Programando
public static int RunPythonFile(string rootDir, string filename)
{
/*
* Create a new engine object
*/
ScriptEngine engine = Python.CreateEngine();
/*
* New source script
*/
ScriptSource source;
source = engine.CreateScriptSourceFromFile(rootDir + filename);
/*
* Create a new scope object
*/
ScriptScope scope = engine.CreateScope();
/*
* Executin the script
*/
int result = source.ExecuteProgram();
return result;
}
}
}
27. Passo 4: Programando
public static int RunPythonFile(string rootDir, string filename)
{
/*
* Create a new engine object Criando o Objeto para
*/ A execução do Script
ScriptEngine engine = Python.CreateEngine();
/*
* New source script
*/
ScriptSource source;
source = engine.CreateScriptSourceFromFile(rootDir + filename);
/*
* Create a new scope object
*/
ScriptScope scope = engine.CreateScope();
/*
* Executin the script
*/
int result = source.ExecuteProgram();
return result;
}
}
}
28. Passo 4: Programando
public static int RunPythonFile(string rootDir, string filename)
{
/* Definindo qual Script
* Create a new engine object Será Executado
*/
ScriptEngine engine = Python.CreateEngine();
/*
* New source script
*/
ScriptSource source;
source = engine.CreateScriptSourceFromFile(rootDir + filename);
/*
* Create a new scope object
*/
ScriptScope scope = engine.CreateScope();
/*
* Executin the script
*/
int result = source.ExecuteProgram();
return result;
}
}
}
29. Passo 4: Programando
public static int RunPythonFile(string rootDir, string filename)
{
/*
* Create a new engine object
*/
ScriptEngine engine = Python.CreateEngine();
Criando um Novo
/* Escopo de execução
* New source script
*/
ScriptSource source;
source = engine.CreateScriptSourceFromFile(rootDir + filename);
/*
* Create a new scope object
*/
ScriptScope scope = engine.CreateScope();
/*
* Executin the script
*/
int result = source.ExecuteProgram();
return result;
}
}
}
30. Passo 4: Programando
public static int RunPythonFile(string rootDir, string filename)
{
/*
* Create a new engine object
*/
ScriptEngine engine = Python.CreateEngine();
/*
* New source script
*/
ScriptSource source;
source = engine.CreateScriptSourceFromFile(rootDir + filename);
/* Colocando o Script para
* Create a new scope object Rodar
*/
ScriptScope scope = engine.CreateScope();
/*
* Executin the script
*/
int result = source.ExecuteProgram();
return result;
}
}
}
33. Passo 6: Criando o Script
O script em IronPython será algo bem simples,
ele irá apenas abrir um novo formulário em
uma nova janela.
Por gerar uma nova janela, a opção de criar
uma nova thread evita que ocorra um erro de
gerenciamento, mas mais importante é que o
novo script acaba sendo executado como uma
função independente, mas que sua
inicialização e finalização está ligada ao
aplicativo original em C#
34. Passo 6: Criando o Script
import clr
import sys
import time
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference('IronPython')
from System.Windows.Forms import Application, Form, Button,
Panel
from System.Drawing import Size
from IronPython.Compiler import CallTarget0
class myForm(Form):
def __init__(self):
self.Text = 'MyApp'
self.CenterToScreen()
self.Size = Size(590,550)
if __name__ == "__main__":
myapp = myForm()
35. Passo 6: Criando o Script
import clr
import sys
import time Adicionando as Referências
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference('IronPython')
from System.Windows.Forms import Application, Form, Button,
Panel
from System.Drawing import Size
from IronPython.Compiler import CallTarget0
class myForm(Form):
def __init__(self):
self.Text = 'MyApp'
self.CenterToScreen()
self.Size = Size(590,550)
if __name__ == "__main__":
myapp = myForm()
36. Passo 6: Criando o Script
import clr
import sys Chamda dos Módulos
import time Necessário
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference('IronPython')
from System.Windows.Forms import Application, Form, Button,
Panel
from System.Drawing import Size
from IronPython.Compiler import CallTarget0
class myForm(Form):
def __init__(self):
self.Text = 'MyApp'
self.CenterToScreen()
self.Size = Size(590,550)
if __name__ == "__main__":
myapp = myForm()
37. Passo 6: Criando o Script
import clr
import sys
import time
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference('IronPython')
Criando a Classe Formulário
from System.Windows.Forms import Application, Form, Button,
Panel
from System.Drawing import Size
from IronPython.Compiler import CallTarget0
class myForm(Form):
def __init__(self):
self.Text = 'MyApp'
self.CenterToScreen()
self.Size = Size(590,550)
if __name__ == "__main__":
myapp = myForm()
38. Passo 6: Criando o Script
import clr
import sys
import time
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference('IronPython')
from System.Windows.Forms import Application, Form, Button,
Panel
from System.Drawing import Size
from IronPython.Compiler import CallTarget0
class myForm(Form): Executando o Programa
def __init__(self):
self.Text = 'MyApp'
self.CenterToScreen()
self.Size = Size(590,550)
if __name__ == "__main__":
myapp = myForm()
39. Adicionado o Script,
Lembrar de mudar para Guardar Script no
diretório onde está o executável
Lembre-se de definir no projeto que o
Script deverá ser copiado para a pasta
onde se encontra o executável no
momento em que será gerada a solução