{"id":89888,"date":"2021-02-11T17:16:40","date_gmt":"2021-02-11T17:16:40","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=89888"},"modified":"2022-04-27T21:07:17","modified_gmt":"2022-04-27T21:07:17","slug":"ironpython-first-steps","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/python\/ironpython-first-steps\/","title":{"rendered":"IronPython: First steps"},"content":{"rendered":"<p>Python is one of the most popular languages for many reasons. Julio Sampaio explains how IronPython allows you to integrate Python with your favorite .NET language.<\/p>\n<p>Have you ever imagined integrating some Python code along with .NET? This idea goes a bit beyond the possibility of <a href=\"https:\/\/www.red-gate.com\/simple-talk\/dotnet\/net-development\/developing-python-with-visual-studio\/\">creating Python code within Visual Studio<\/a>, although that\u2019s an important step towards such a goal. <a href=\"https:\/\/ironpython.net\/\">IronPython<\/a> is a way to accomplish this integration. It is an open-source implementation of the Python language to allow closer integration with the .NET Framework.<\/p>\n<p>IronPython works as an extension to the .NET Framework, but it can also be used by .NET projects to take advantage of Python\u2019s scripting power. Other than that, since IronPython is a real implementation of Python itself, there\u2019s no need to learn a new language or extra features if you already know Python.<\/p>\n<p>This article explores the language and teaches how you can benefit from its integration with .NET.<\/p>\n<h2><a id=\"post-89888-_heading=h.30j0zll\"><\/a>Setup<\/h2>\n<p>There are a couple of ways to install it. If you aim to use IronPython standalone in projects other than those in Visual Studio, you can download and install it. Examples in this article use the 2.7.11 release, but the examples should work well with the latest version.<\/p>\n<p>Go to the GitHub <a href=\"https:\/\/github.com\/IronLanguages\/ironpython2\/releases\/tag\/ipy-2.7.11\">download page<\/a>, and click the MSI installer to download it. I\u2019m assuming you\u2019re following this tutorial from a Windows OS. Visual Studio still has no support for adding Python extensions on macOS, for instance.<\/p>\n<p>Run the installer and follow the steps until the end.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-89889\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-90.png\" alt=\"IronPython setup wizard\" width=\"587\" height=\"460\" \/><\/p>\n<p><strong>Figure 1.<\/strong> <strong>Installing IronPython on Windows.<\/strong><\/p>\n<p>During the process, you may notice a screen that shows the Python versions being installed (Figure 2). It comes by default with Python\u2019s IronPython language, along with the <a href=\"https:\/\/pypi.org\/project\/pip\/\">pip<\/a> (package manager for Python).<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-89890\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-91.png\" alt=\"IronPython setup\" width=\"587\" height=\"460\" \/><\/p>\n<p><strong>Figure 2.<\/strong> <strong>Selecting the IronPython features<\/strong>.<\/p>\n<p>Make sure to browse for the installation location shown in Figure 2 if you won\u2019t use the default one. After the process is done, you can go to the specified folder and run the file <em>ipy.exe<\/em>. It represents the command line interface from which you may run your IronPython commands.<\/p>\n<p>Run it, and check in Figure 3 how the interface looks.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-89891\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-92.png\" alt=\"check the interface\" width=\"791\" height=\"387\" \/><\/p>\n<p><strong>Figure 3. IronPython command-line shell.<\/strong><\/p>\n<p>It is also a REPL, which allows you to execute interactive Python code to try it out. Do it as you please.<\/p>\n<p>Alternatively, you can also download IronPython binary files, extract them and access the executor via the command line. We\u2019ll stick, however, to the installer-based version which is more concise and straightforward.<\/p>\n<h2><a id=\"post-89888-_heading=h.1fob9te\"><\/a>WinForms with IronPython<\/h2>\n<p>Now that you have the environment set up, it\u2019s time to learn what IronPython is capable of doing. Perhaps one of the best ways to prove its interoperability with .NET is through the construction of some WinForms.<\/p>\n<p>To see this in action, you will create a simple <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.windows.forms.messagebox\">MessageBox<\/a> to display a message window and two buttons: <em>Yes<\/em> and <em>No<\/em>. Figure 4 illustrates how the box is going to look .<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-89892\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-93.png\" alt=\"MessageBox with IronPython\" width=\"252\" height=\"166\" \/><\/p>\n<p><strong>Figure 4.<\/strong> <strong>A MessageBox built with IronPython<\/strong>.<\/p>\n<p>Each operation is going to run some Python code to perform different actions. You can find the code for this in Listing 1.<\/p>\n<p><strong>Listing 1.<\/strong> <strong>Creating a box with action buttons.<\/strong><\/p>\n<pre class=\"lang:c# theme:vs2012\">import clr\r\nclr.AddReference('System')\r\nclr.AddReference('System.Windows.Forms')\r\nimport System\r\nimport System.Windows.Forms as WinForms\r\nmessage = \"Cancel this operation?\"\r\ncaption = \"Alert\"\r\nbuttons = WinForms.MessageBoxButtons.YesNo\r\nresult = WinForms.MessageBox.Show(message, caption, buttons)\r\nif result == WinForms.DialogResult.Yes:\r\n    WinForms.MessageBox.Show(\"Great, it's canceled!\")\r\n    System.Console.Write(\"Success!\")\r\nelse:\r\n    print \"Sorry, something went wrong!\"<\/pre>\n<p>If you\u2019ve coded with Python and C# before, this code may look weirdly familiar.<\/p>\n<p>The starting point of any mixed code with IronPython starts with its <a href=\"https:\/\/docs.microsoft.com\/en-us\/archive\/msdn-magazine\/2006\/october\/clr-inside-out-ironpython\">CLR module<\/a> (the common language runtime). It allows a deep integration between both languages. With it in hand, you can add as many references as you want, such as the <code>System<\/code> and the Windows Forms.<\/p>\n<p>Take note of how the whole coding experience is Python-based, and only Python. This includes the imports, the variables, the code indentation, the conditional statements, etc.<\/p>\n<p>Once you add the .NET references, you\u2019re allowed to use them throughout the code as real Python objects. The methods, types, parameters, and results also apply, so be careful. Also, pay attention to the body of the if condition. In case the user selects the option \u201cYes\u201d, another message box is displayed along with a logline coded in C# via <code>System.Console<\/code>. Otherwise, the negative log is displayed but this time via Python\u2019s <code>print<\/code> function. Cool, isn\u2019t it?<\/p>\n<p>Save the code to a file called <em>Hello.py<\/em> into the same folder that IronPython is installed. Then, open a standard command line (<code>cmd<\/code>), navigate to the IronPython root folder:<\/p>\n<pre class=\"lang:none theme:none\">cd C:\\Program Files\\IronPython 2.7<\/pre>\n<p>Then run the following command:<\/p>\n<pre class=\"lang:none theme:none\">ipy.exe Hello.py<\/pre>\n<p>The execution triggers the message box shown in Figure 4. Go ahead and test both the buttons. Figure 5 shows what happens after clicking the <em>Yes <\/em>option.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"181\" height=\"166\" class=\"wp-image-89893\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-94.png\" \/><\/p>\n<p><strong>Figure 5.<\/strong> <strong>Message box opened after <em>Yes<\/em> option-click.<\/strong><\/p>\n<p>The image above will be followed by the message \u201cSuccess\u201d logged in the console.<\/p>\n<h2><a id=\"post-89888-_heading=h.3znysh7\"><\/a>Dealing with generics<\/h2>\n<p>Generics are an important part of Object-oriented programming, and IronPython allows its usage along with some Python code. Take the classic example of <code>Collections<\/code>. They represent one of the most traditional uses of generics in C#. Check out the code presented in Listing 2.<\/p>\n<p><strong>Listing 2.<\/strong> <strong>Dealing with Generics in IronPython<\/strong><\/p>\n<pre class=\"lang:c# theme:vs2012\">from System.Collections.Generic import List\r\nitems = List[str]()\r\nitems.Add('Item A')\r\nitems.Add('Item B')\r\nitems.Add('Item C')\r\nfor item in items:\r\n print item<\/pre>\n<p>Note how array-like this syntax is. Yes, you can provide IronPython with generics just the way you access array indices. If you try to add anything other than strings, like shown below:<\/p>\n<pre class=\"lang:c# theme:vs2012\">items = List[str]()\r\nitems.Add(123)<\/pre>\n<p>A corresponding error will be thrown:<\/p>\n<pre class=\"lang:c# theme:vs2012\">Traceback (most recent call last):\r\n  File \"Hello.py\", line 3, in &lt;module&gt;\r\nTypeError: expected str, got int<\/pre>\n<h2><a id=\"post-89888-_heading=h.2et92p0\"><\/a>Object-oriented programming<\/h2>\n<p>OOP is another crucial part when it comes to C# development. Among its many facets, being able to create classes (along with attributes and methods) and instantiate objects is also possible in IronPython. To demonstrate, change the content of your <em>Hello.py <\/em>file with the code shown in Listing 3.<\/p>\n<p><strong>Listing 3.<\/strong> <strong>Example of a C# class in IronPython<\/strong><\/p>\n<pre class=\"lang:c# theme:vs2012\">class Person:\r\n    name = 'John Silva'\r\n    age = 12\r\n    email = 'john@email.com'\r\n    \r\n    # setters\r\n    def setName(self, name):\r\n        self.name = name\r\n    def setAge(self, age):\r\n        self.age = age\r\n    def setEmail(self, email):\r\n        self.email = email\r\n        \r\n    # getters\r\n    def getName(self):\r\n        return self.name\r\n    def getAge(self):\r\n        return self.age\r\n    def getEmail(self):\r\n        return self.email\r\n    def getInfo(self):\r\n        print \"Hi! I'm \", self.name, \", I'm \", self.age, \"years old and this is my email: \", self.email<\/pre>\n<p>Pretty simple. There\u2019s just a couple of attributes and getters\/setters for each. To make use of this class, you\u2019d have to import it within another Python file. However, to simplify it, open another command line window and <em>cd<\/em> into the folder where the <em>Hello.py<\/em> file is located. Then, execute the command below in order to let <em>ipy<\/em> notice that specific class:<\/p>\n<pre class=\"lang:none theme:none\">ipy Hello.py<\/pre>\n<p>Now, it\u2019s time to enter into the interactive mode. Just hit the ipy command for that, and the terminal must change to how it is shown in Figure 6.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"870\" height=\"437\" class=\"wp-image-89894\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-95.png\" \/><\/p>\n<p><strong>Figure 6.<\/strong> <strong>IronPython interactive mode.<\/strong><\/p>\n<p>Then, you can run some interactive code exploring the <code>Person<\/code> class previously created. Type the following code lines directly to the new shell window:<\/p>\n<pre class=\"lang:c# theme:vs2012\">import sys\r\nsys.path.append('C:\\Program Files\\IronPython 2.7')\r\nimport Hello<\/pre>\n<p>Make sure to change IronPython\u2019s path with yours. Finally, play with it by creating a person object and calling its methods:<\/p>\n<pre class=\"lang:c# theme:vs2012\">person = Hello.Person()\r\nperson.getInfo()\r\n&gt; Hi! I'm  John Silva, I'm  12 years old and this is my email:  john@email.com<\/pre>\n<p>Figure 7 shows a bit more of the options you can base at.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"870\" height=\"437\" class=\"wp-image-89895\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2021\/02\/word-image-96.png\" \/><\/p>\n<p><strong>Figure 7.<\/strong> <strong>Playing with Person object\u2019s methods in IronPython.<\/strong><\/p>\n<h2><a id=\"post-89888-_heading=h.tyjcwt\"><\/a>What else can you do with IronPython?<\/h2>\n<p>IronPython can work for many of the .NET facets, such as ASP.NET web applications, APIs, data science, etc., but it\u2019s been more widely used for desktop application development.<\/p>\n<p>There used to be an IronPython Studio to integrate with Visual Studio 2008. However, time and maintenance have proved too difficult to keep up with. Today, you can add IronPython\u2019s dependencies to your .NET projects via NuGet, especially if you\u2019re working with Visual Studio.<\/p>\n<p>It\u2019s important to note that IronPython has been around for quite a long time, and still, the team has been working to maintain and update it. The <a href=\"https:\/\/ironpython.net\/documentation\/\">documentation<\/a> is not complete, but it\u2019s enough to make some grounds when getting started. Additionally, the classic book <a href=\"http:\/\/www.ironpythoninaction.com\/\">IronPython in Action<\/a> is a must-read if you\u2019re willing to understand more about its capability.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is one of the most popular languages. Julio Sampaio explains how IronPython allows you to integrate Python with .NET.&hellip;<\/p>\n","protected":false},"author":323407,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[146042],"tags":[5647,5021,5134],"coauthors":[93894],"class_list":["post-89888","post","type-post","status-publish","format-standard","hentry","category-python","tag-ironpython","tag-python","tag-sql-prompt"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89888","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/323407"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=89888"}],"version-history":[{"count":4,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89888\/revisions"}],"predecessor-version":[{"id":89897,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89888\/revisions\/89897"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=89888"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=89888"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=89888"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=89888"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}