Tutorial Rodando Python no C#

Post on 15-May-2015

1.306 views 2 download

Transcript of Tutorial Rodando Python no C#

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

Por: Eduardo dos Santos PereiraDr. em Astrofísica

pereira.somoza@gmail.com

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

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

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.

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

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

Abrindo o Formulário

Abrindo Formulário

Criar Botão para Chamar o Script

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

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.

Adicionar Referências

Adicionando Referências

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

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

O código para a Chamada

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:

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;

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

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.

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

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

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

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

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.

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

}}

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

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

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

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

Passo 5: Criar a Pastas que conterá os scripts

Passo 6: Criando o Script

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#

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)

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

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

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

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

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

Adicionado o Script,Lembrar de mudar para Guardar Script no

diretório onde está o executável

Rodando no Modo Debug

FIM