- Saved searches
- Use saved searches to filter your results more quickly
- License
- IronLanguages/ironpython3
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- User
- Other Python-Like Languages for .NET/Mono
- Accessing .NET from CPython
- Поговорим про IronPython
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
License
IronLanguages/ironpython3
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
* Fix leak in FileManager * Fix more leaks * Update after review
Git stats
Files
Failed to load latest commit information.
README.md
There is still much that needs to be done to support Python 3.x. We are working on it, albeit slowly. We welcome all those who would like to help!
IronPython is an open-source implementation of the Python programming language that is tightly integrated with .NET. IronPython can use .NET and Python libraries, and other .NET languages can use Python code just as easily.
IronPython 3 targets Python 3, including the re-organized standard library, Unicode strings, and all of the other new features.
What? | Where? |
---|---|
Windows/Linux/macOS Builds | |
Downloads | |
Help |
using System.Windows.Forms; MessageBox.Show("Hello World!", "Greetings", MessageBoxButtons.OKCancel);
can be written in IronPython as follows:
import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox, MessageBoxButtons MessageBox.Show("Hello World!", "Greetings", MessageBoxButtons.OKCancel)
Here is an example how to call Python code from a C# program.
var eng = IronPython.Hosting.Python.CreateEngine(); var scope = eng.CreateScope(); eng.Execute(@" def greetings(name): return 'Hello ' + name.title() + '!' ", scope); dynamic greetings = scope.GetVariable("greetings"); System.Console.WriteLine(greetings("world"));
This example assumes that IronPython has been added to the C# project as a NuGet package.
This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information see the .NET Foundation Code of Conduct.
The current target is Python 3.4, although features and behaviors from later versions may be included.
See the following lists for features from each version of CPython that have been implemented:
For details on contributing see the Contributing article.
Upgrading from IronPython 2
For details on upgrading from IronPython 2 to 3 see the Upgrading from IronPython 2 to 3 article.
While compatibility with CPython is one of our main goals with IronPython 3, there are still some differences that may cause issues. See Differences from CPython for details.
See the Package compatibility document for information on compatibility with popular packages.
Binaries of IronPython 3 can be downloaded from the release page, available in various formats: .msi , .zip , .deb , .pkg . The IronPython package is also available on NuGet. See the installation document for detailed instructions on how to install a standalone IronPython interpreter on various operating systems and .NET frameworks.
See the building document. Since the main development is on Windows, bugs on other platforms may inadvertently be introduced — please report them!
IronPython 3 targets .NET Framework 4.6.2, .NET Standard 2.0, .NET Core 3.1 and .NET 6.0. The support for .NET and .NET Core follow the lifecycle defined on .NET and .NET Core Support Policy.
About
Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
User
IronPython is an open source implementation of Python for the .NET CLR and Mono, originally created by Jim Hugunin.
You can get news and download the latest version fromt the projects website: https://ironpython.net/
IronPython uses the Dynamic Language Runtime, a framework for writing dynamic languages for .NET which originated in IronPython 1. It also runs on Silverlight, a .NET browser plugin that runs on Windows and the Mac (and a Mono port called Moonlight runs on Linux). This means that IronPython can be used for client-side scripting in the browser.
IronPython is a Python compiler. It compiles Python code to in memory bytecode before execution (which can be saved to disk, making binary only distributions possible).
Performance is comparable to CPython — much faster for some things (where it can take advantage of the JIT compiler in the underlying platform), but slower for other things (particularly the built in container types where a lot of work has been done on optimising the CPython types).
- Corporate credibility (introducing new technologies can be very difficult in some companies, if .NET is already established then you may need no excuse to start using IronPython)
- No GlobalInterpreterLock — IronPython has no GIL and multi-threaded code can use multi core processors
- The .NET framework library is very big. Particularly the user interface library Windows Forms is very good.
- IronPython is easy to embed in .NET applications as a scripting language
- Easier to extend than CPython (C# is memory managed and C# types can be used directly in IronPython with no wrapping)
- Silverlight!
A book on IronPython for Python and .NET developers: IronPython in Action.
A useful resource for IronPython code examples, is the IronPython Cookbook (archive).
A book that introduces core concepts of IronPython programming using a .NET–centric approach is Pro IronPython.
Mozilla announced a project to port the DLR (well, the underlying Core CLR that it uses in fact) to run on their Tamarin JIT. This means that IronPython could also run in future versions of Firefox. (See IronMonkey). Unfortunately this project has not made any progress since its announcement.
Other Python-Like Languages for .NET/Mono
- BooLanguage — Syntax is very similar to Python’s, yet the language is statically compiled. It implements many features that have been suggested for Python3.0. See Gotchas for Python Users (archive) for specific comparisons between boo and CPython.
- Cobra Language
Accessing .NET from CPython
Python for .NET (archive) is the reverse of IronPython, it lets you access .NET assemblies from CPython.
See also: PythonAndParrot, LoGix, IronPython IDE
IronPython (last edited 2022-09-25 12:38:41 by HuntBlanchat )
Поговорим про IronPython
Расскажем об интересном проекте IronPython. Описание звучит так: «IronPython — это реализация языка программирования Python с открытым исходным кодом, которая тесно интегрирована с .NET Framework. IronPython может использовать библиотеки .NET Framework и Python, а другие языки .NET могут также легко использовать код Python».
Для начала установим все необходимое. Для работы с данным проектом нам понадобиться Visual Studio (мы используем 2019,. Net Framework необходим не ниже 4.5,. Net Core 2.0 или 2.1). Установить можно через менеджер Nuget Install-Package IronPython Install-Package IronPython.StdLib. Текущая, на момент написания статьи, версия – 2.7.10.
Для начала создадим приложение Windows Forms и добавим туда все, что требуется:
В этот раз не будем пытаться решать сложных проблем, придумаем что-нибудь простое и одновременно показывающее взаимодействие Python и C#. Пусть нам необходимо сложить 2 числа (и мы по каким-то причинам не хотим делать эту операцию обыкновенным способом «в столбик» или с помощью калькулятора). Для этого добавим на нашу форму 3 TextBox-а, пару Label-ов и один Button. Должно получиться примерно так:
В первые два текстовых поля мы будем вводить наши значения, а в третьем пусть отображается наш результат.
Стоит отметить, что все, что будет взаимодействовать с IronPython, должно быть «public».
Существует несколько методов для работы со скриптами в Ironpython:
Нам больше всего нравится способ ExecuteFile(), его и будем использовать. Для этого в метод инициализации формы добавим следующее:
engine = IronPython.Hosting.Python.CreateEngine(); scope = engine.CreateScope(); scope.SetVariable(«Main», this);
Для того, чтобы выполнить какой-нибудь скрипт, добавим в код метода обработки кнопки следующий код:
В указанном выше коде выполняется построчно следующее:
- Исполняется файл по указанному адресу, в котором определена функция,
- Функция из Python определяется в C#,
- Вычисляется значение функции с учетом введенных значений,
- В текстовое поле, предполагавшееся для ответа, записывается результат арифметической операции либо ошибка, которая возникла при выполнении.
Ну и сам Python-файл с функцией содержит код:
Проверим, как работает наш «вычислитель»:
Верно! У нас получилось написать простейшее приложение с применением этой технологии. Кажется, мы решили «детскую» задачку – написали простейший калькулятор, который умеет только складывать два числа. Но разве не с простых «детских» задач начинается изучение чего-то нового?!Это неплохая возможность в изучении с использованием уже знакомых инструментов. С помощью IronPython можно не только интерпретировать некоторый код, но и проводить некоторые параллели при изучении Python. К примеру, код на C#:
namespace IronPython.Example < class Program < static void Main(string[] args) < string blurb = String.Format("<0>«, «Hello World! The current date and time is «, DateTime.Now); Console.WriteLine(blurb); > > >0>
Будет эквивалентен следующему коду на IronPython:
from System import DateTime, String blurb = String.Format(» <0>«, «Hello World! The current date and time is «, DateTime.Now) print blurb0>
Есть некоторое сходство, верно?!
Если в течение какого-то продолжительного времени вы писали .Net приложения традиционным способом (запись, компиляция, тестирование, исправление, перекомпиляция, повторное тестирование, все сначала) и по каким-то причинам столкнулись с необходимостью работы со скриптами (даже необязательно для анализа данных), то IronPython может стать своеобразным «мостом» для перехода к написанию скриптов Python и подарит возможность взглянуть на некоторые вещи под иным углом.