• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Tutorial Rodando Python no C#
 

Tutorial Rodando Python no C#

on

  • 1,241 views

 

Statistics

Views

Total Views
1,241
Views on SlideShare
1,147
Embed Views
94

Actions

Likes
0
Downloads
16
Comments
0

6 Embeds 94

http://gravywave.blogspot.com.br 83
http://gravywave.blogspot.com 3
http://feeds.feedburner.com 3
http://gravywave.blogspot.it 2
http://gravywave.blogspot.pt 2
http://gravywave.blogspot.com.ar 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Tutorial Rodando Python no C# Tutorial Rodando Python no C# Presentation Transcript

    • Tutorial [Introdutório]: Criando Pluging IronPython para c# Por: Eduardo dos Santos Pereira Dr. em Astrofísica pereira.somoza@gmail.com
    • Tutorial [Introdutório]: Criando Pluging IronPython para c# Instituto Nacional de Pesquisas Espaciais/DEAApresentado uma breve introdução de comorodar um script IronPython dentro do C#, issopermitiria a criação de plugins em IronPythonpara projetos que originalmente forma escritosem 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 dlls 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 SejamCopiadas 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; Gerado pelo Visual Studiousing 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 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;
    • 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; Chamando O IronPythonusing System.Reflection; E o Microsoft.Scripting parausing 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;
    • Passo 4: Programandonamespace 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: Programandonamespace 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); }
    • Passo 4: Programandonamespace 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); }
    • Passo 4: Programandonamespace 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); }
    • 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 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; } }}
    • Passo 4: Programandopublic 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; } }}
    • Passo 4: Programandopublic 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; } }}
    • 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); /* Colocando o Script para * Create a new scope object Rodar */ ScriptScope scope = engine.CreateScope(); /* * Executin the script */ int result = source.ExecuteProgram(); return result; } }}
    • 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 Sizefrom IronPython.Compiler import CallTarget0class myForm(Form): def __init__(self): self.Text = MyApp self.CenterToScreen() self.Size = Size(590,550)if __name__ == "__main__": myapp = myForm()
    • Passo 6: Criando o Scriptimport clrimport sysimport time Adicionando as Referênciasclr.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 Sizefrom IronPython.Compiler import CallTarget0class myForm(Form): def __init__(self): self.Text = MyApp self.CenterToScreen() self.Size = Size(590,550)if __name__ == "__main__": myapp = myForm()
    • Passo 6: Criando o Scriptimport clrimport sys Chamda dos Módulosimport time Necessárioclr.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 Sizefrom IronPython.Compiler import CallTarget0class myForm(Form): def __init__(self): self.Text = MyApp self.CenterToScreen() self.Size = Size(590,550)if __name__ == "__main__": myapp = myForm()
    • Passo 6: Criando o Scriptimport clrimport sysimport timeclr.AddReference("System")clr.AddReference("System.Windows.Forms")clr.AddReference("System.Drawing")clr.AddReference(IronPython) Criando a Classe Formuláriofrom System.Windows.Forms import Application, Form, Button,Panelfrom System.Drawing import Sizefrom IronPython.Compiler import CallTarget0class myForm(Form): def __init__(self): self.Text = MyApp self.CenterToScreen() self.Size = Size(590,550)if __name__ == "__main__": myapp = myForm()
    • 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 Sizefrom IronPython.Compiler import CallTarget0class myForm(Form): Executando o Programa def __init__(self): self.Text = MyApp self.CenterToScreen() self.Size = Size(590,550)if __name__ == "__main__": myapp = myForm()
    • 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