tutorial rodando python no c#

42
Tutorial [Introdutório]: Criando Pluging IronPython para c# Por: Eduardo dos Santos Pereira Dr. em Astrofísica [email protected]

Upload: eduardo-s-pereira

Post on 15-May-2015

1.306 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Tutorial Rodando Python no C#

Tutorial [Introdutório]: Criando Pluging IronPython para c#

Por: Eduardo dos Santos PereiraDr. em Astrofísica

[email protected]

Page 2: Tutorial Rodando Python no C#

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#.

Page 3: Tutorial Rodando Python no C#

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

Page 4: Tutorial Rodando Python no C#

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.

Page 5: Tutorial Rodando Python no C#

Passo 1: Criação de Uma Nova Solução

Page 6: Tutorial Rodando Python no C#

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

Page 7: Tutorial Rodando Python no C#

Abrindo o Formulário

Page 8: Tutorial Rodando Python no C#

Abrindo Formulário

Page 9: Tutorial Rodando Python no C#

Criar Botão para Chamar o Script

Page 10: Tutorial Rodando Python no C#

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

Page 11: Tutorial Rodando Python no C#

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.

Page 12: Tutorial Rodando Python no C#

Adicionar Referências

Page 13: Tutorial Rodando Python no C#

Adicionando Referências

Page 14: Tutorial Rodando Python no C#

Definindo para que as Referências Sejam Copiadas para o Diretório do Executável Final

Page 15: Tutorial Rodando Python no C#

Fazer com que as Referências do IronPython sejam salvas no Diretório do Executável

Page 16: Tutorial Rodando Python no C#

O código para a Chamada

Page 17: Tutorial Rodando Python no C#

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:

Page 18: Tutorial Rodando Python no C#

Passo 4: Programandousing 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;

Page 19: Tutorial Rodando Python no C#

Passo 4: Programandousing 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;

Gerado pelo Visual Studio

Page 20: Tutorial Rodando Python no C#

Passo 4: Programandousing 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;

Usando Referências ImportantesDo Sistema.

Page 21: Tutorial Rodando Python no C#

Passo 4: Programandousing 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;

Chamando O IronPython E o Microsoft.Scripting para

Trabalhar

Page 22: Tutorial Rodando Python no C#

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); }

Page 23: Tutorial Rodando Python no C#

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); }

Código Gerado Pelo Visual Studio

Page 24: Tutorial Rodando Python no C#

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); }

A Função que Chama O Script será ExecutadaComo uma nova Thread

Page 25: Tutorial Rodando Python no C#

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); }

Aqui são definidas as variáveis filename, que informa o

A pastas e o script que será Executado.

Além disso é definido o diretórioOnde está o executável.

Page 26: Tutorial Rodando Python no C#

Passo 4: Programandopublic 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; }

}}

Page 27: Tutorial Rodando Python no C#

Passo 4: Programandopublic 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; }

}}

Criando o Objeto para A execução do Script

Page 28: Tutorial Rodando Python no C#

Passo 4: Programandopublic 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; }

}}

Definindo qual Script Será Executado

Page 29: Tutorial Rodando Python no C#

Passo 4: Programandopublic 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; }

}}

Criando um NovoEscopo de execução

Page 30: Tutorial Rodando Python no C#

Passo 4: Programandopublic 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; }

}}

Colocando o Script para Rodar

Page 31: Tutorial Rodando Python no C#

Passo 5: Criar a Pastas que conterá os scripts

Page 32: Tutorial Rodando Python no C#

Passo 6: Criando o Script

Page 33: Tutorial Rodando Python no C#

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#

Page 34: Tutorial Rodando Python no C#

Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference('IronPython')

from System.Windows.Forms import Application, Form, Button, Panelfrom 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() Application.Run(myapp)

Page 35: Tutorial Rodando Python no C#

Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference('IronPython')

from System.Windows.Forms import Application, Form, Button, Panelfrom 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() Application.Run(myapp)

Adicionando as Referências

Page 36: Tutorial Rodando Python no C#

Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference('IronPython')

from System.Windows.Forms import Application, Form, Button, Panelfrom 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() Application.Run(myapp)

Chamda dos Módulos Necessário

Page 37: Tutorial Rodando Python no C#

Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference('IronPython')

from System.Windows.Forms import Application, Form, Button, Panelfrom 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() Application.Run(myapp)

Criando a Classe Formulário

Page 38: Tutorial Rodando Python no C#

Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference('IronPython')

from System.Windows.Forms import Application, Form, Button, Panelfrom 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() Application.Run(myapp)

Executando o Programa

Page 39: Tutorial Rodando Python no C#

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

Page 40: Tutorial Rodando Python no C#

Adicionado o Script,Lembrar de mudar para Guardar Script no

diretório onde está o executável

Page 41: Tutorial Rodando Python no C#

Rodando no Modo Debug

Page 42: Tutorial Rodando Python no C#

FIM