Re: [Python.NET] surveying the landscape ...
i'm still new with ironpython, along with using python 2.7, platformio, pyserial, pyvisa. I am an EE who cross trained into MS .NET programming from embedded micro-controller systems development and manufacturing. I primarily use python on embedded linux systems such as beaglebone black, raspberry pi, seeeduino arch. although i also have netduino devices running MS .NET micro framework. does python.net run on .net micro framework? thanks Ron “The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind. ”Nikola Tesla“Radio Power Will Revolutionize the World” (Modern Mechanix & Inventions, July, 1934) On Tuesday, June 16, 2015 2:37 AM, Tony Roberts wrote: Hi Adam, from my point of view it'd be great to have more people involved. I've been doing some development, but more or less out of necessity (I enjoy working on the project when I can, but don't really have the time to commit to it much more than I have been unfortunately). To give you some background around why there's the renshawbay repo as well as the main repo; Initially I created the renshawbay repo as there were various changes I needed to make to the project while it was hosted in sourceforge, and for me it was easier to manage that in github. I added Python 3 support, and later some stuff around subclassing .net classes in Python. It was then decided to move the project to github, so we created the pythonnet repo directly from the sourceforge repo rather than fork the renshawbay repo. The thinking back then was that we should do a 2.0 release based off that fork, and then once that was stable look at merging in the Python 3 work from the renshawbay fork. So, to answer your first question - pythonnet/pythonnet is the official repo, but most new development (new features etc) has taken place on the renshawbay/pythonnet fork in the python3 branch (which maintains support for Python 2). There's no official roadmap that I'm aware of. There are some issues and milestones in the github repo, but AFAIK no one is actively working on those right now. There are only a couple of issues remaining for the 2.0 release however. Pull requests to the official repo are reviewed and merged by the project owners (of which I'm one). So far those have been bug fixes or changes necessary for the 2.0 release. I keep the renshawbay fork up to date with any commits to the main repo. For what it's worth, here's what I'm aware of that needs attention: - Finalizing and releasing to PyPI the 2.0 release for Python 2.x only - Testing and getting the renshawbay python3 branch working on non-windows platforms (the linux build currently has problems, and I've not tested any mac builds) - Merging the renshawbay python3 branch into the main pythonnet fork - Updating the docs If you're able to help at all that would be much appreciated. Best regards,Tony On Tue, Jun 16, 2015 at 12:08 AM Tribble, Brett wrote: Adam, I’m ecstatic that there’s a player out there who is making good use of Python.net, and who would like to help contribute. Organizational and logistical issues aside, I’m all for anything you can throw at the project! Someone correct me if I’m wrong, but I believe Brian Lloyd has largely yielded this project to Tony and the community. Based on Brian and Tony’s past posts, I’m fairly sure they’ll welcome any and all contributions to the project. It may sound sacrilegious to some, but I would love to see the PTVS (https://pytools.codeplex.com/) folks get involved with the project. They’re turning out a solid product, and this fits solidly in with what Microsoft is trying to do with PTVS, .NET Core, Azure etc. From: PythonDotNet [mailto:pythondotnet-bounces+btribble=ea@python.org]On Behalf Of Brad Friedman Sent: Monday, June 15, 2015 2:36 PM To: A list for users and developers of Python for .NET Subject: Re: [Python.NET] surveying the landscape ... I'll chime in and say the lack of these kinds of legitimate "stake-holder" systems and responsibilities has forced me to turn away from depending my work on this project. I still keep up on it in hopes that it will turn around. If a legitimate player were to step up and contribute to a responsible, active and stable future for the project, I'd likely reconsider my stance and begin active support again. It's hard to justify putting much into it as one guy with limited resources. It needs full multi-platform release and development support both as a python module and a .net embedding toolkit, both for Python 2.x and 3.x. That's a lot of work to commit to getting set right and maintaining. On Jun 15, 2015, at 3:57 PM, Adam Klein wrote: Hello all, We are usingPython.NET at BlueMountain to interface between our large .NET code base and the cpython ecosystem for interactive, exploratory computing. By way of background, I was a major contributor to the pandas library for a time; my firm
Re: [Python.NET] Getting an open Python file handle into CLR
perhaps re-directed command line calls for stdin, stdout, stderr in c# interacting with python i/o command line calls(although in python it is common practice to daisy chain commands). i have used this many times to get out of scrapes for 3rd party process calls in c#. good luck! Ron “The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind. ”Nikola Tesla“Radio Power Will Revolutionize the World” (Modern Mechanix & Inventions, July, 1934) On Monday, July 20, 2015 9:05 PM, Dan Lenski wrote: Hi, I posted this on StackOverflow but thought it might be a better question for this mailing list. http://stackoverflow.com/questions/31530059/how-can-i-open-a-net- filestream-object-from-a-python-file-handle I'm trying to figure out how to transform an open Python file handle into a System.IO.FileStream object so that I can pass it to C# code. Here's what I've got so far. This produces the good ol' win32 (HANDLE*) object, I believe: import clr, msvcrt from Microsoft.Win32.SafeHandles import SafeFileHandle from System.IO import FileStream, FileAccess from System import IntPtr, Int32, Int64 pyf=open("c:/temp/testing123.txt","w") fileno=pyf.fileno() print fileno # 6 handle = msvcrt.get_osfhandle(fileno) print handle # 1832L Unfortunately, I can't figure out how to convince the clr module to cast this handle into something that I can use as an IntPtr, as required by the constructors of FileStream or SafeFileHandle. I've tried various versions of the following, but they all give me TypeError ("value cannot be converted to System.IntPtr"): FileStream(IntPtr(handle), True) FileStream(IntPtr(Int32(handle), True) SafeFileHandle(IntPtr(handle), True) Thanks, Dan Lenski _ Python.NET mailing list - PythonDotNet@python.org https://mail.python.org/mailman/listinfo/pythondotnet _ Python.NET mailing list - PythonDotNet@python.org https://mail.python.org/mailman/listinfo/pythondotnet
Re: [Python.NET] Getting an open Python file handle into CLR
>how do I cast a win32 file handle to an IntPtr? i ran into this in the past as well; specifically when i started using FTDI USB devices on DLPdesign development kits. the library is written in c++ MFC code. After providing data marshal/platform invoke i applied the intptr in c#. The USB device that I am accessing, passes a file handle to indicate specific pass / fail condition. i.e. the first command opens a connection to the device, the expected handle is 'OK'. if not one of many different possible error messages is passed in the file handle. SummaryOpen the device and return a handle which will be used for subsequent accesses.DefinitionFT_STATUS FT_Open (int iDevice, FT_HANDLE *ftHandle)ParametersiDevice Index of the device to open. Indices are 0 based.ftHandle Pointer to a variable of type FT_HANDLE where the handle will bestored. This handle must be used to access the device.Return ValueFT_OK if successful, otherwise the return value is an FT error code. public class Wrapper{private static IntPtr m_USBhandler; [DllImport("FTD2XX.dll", EntryPoint="FT_Open")]public static extern uint FT_Open(int iDevice, ref IntPtr ftHandle); [DllImport("FTD2XX.dll", EntryPoint="FT_Close")]public static extern uint FT_Close(IntPtr ftHandle); [DllImport("FTD2XX.dll", EntryPoint="FT_Read")]public static extern uint FT_Read(IntPtr ftHandle, byte[] lpBuffer,uint dwBytesToRead, ref uintlpdwBytesReturned); [DllImport("FTD2XX.dll", EntryPoint="FT_Write")]public static extern uint FT_Write(IntPtr ftHandle, byte[] lpBuffer,uint dwBytesToWrite, ref uintlpdwBytesWritten); [DllImport("FTD2XX.dll", EntryPoint="FT_Purge")]public static extern uint FT_Purge(IntPtr ftHandle, uint dwMask); public static bool OpenDevice(){if (((FT_Status)Wrapper.FT_Open(1, ref m_USBhandler)) ==FT_Status.Ok){return true;}else{return false;}} i hope this helps you by seeing one way of applying file handles in c#. Ron “The desire that guides me in all I do is the desire to harness the forces of nature to the service of mankind.”Nikola Tesla“Radio Power Will Revolutionize the World” (Modern Mechanix & Inventions, July, 1934) On Tuesday, July 21, 2015 11:12 AM, Dan Lenski wrote: Ron Harding via PythonDotNet writes: > perhaps re-directed command line calls for stdin, stdout, stderr in c# interacting with python i/o command line calls(although in python it is common practice to daisy chain commands). Unfortunately, I cannot redirect the output of the C# library to a convenient filehandle like stdout/stderr; I need to be specify a FileStream object. It pretty much comes down to this: how do I cast a win32 file handle to an IntPtr? Thanks, Dan _ Python.NET mailing list - PythonDotNet@python.org https://mail.python.org/mailman/listinfo/pythondotnet _ Python.NET mailing list - PythonDotNet@python.org https://mail.python.org/mailman/listinfo/pythondotnet
Re: [Python.NET] Embedding a Python interactive shell in a .NET application
sounds great; one additional suggestion, don't just use a plane jane .net text box, but instead use a 'rich text box'. why? i have used it again and again in smart terminal emulator windows where properties like 'append' are built in, plus it is easy to build in self scrolling, and colored prompts for different data i.e. >>>output, << wrote: Just in case someone stumbles on this post looking for an answer:A solution that worked for me was redirecting the Python stdout/stderr to a stream in Python. I was then able to route this stream into the .NET text box.private void button1_Click(object sender, EventArgs e) { using (Py.GIL()) { // Redirect stdout to text box dynamic sys = PythonEngine.ImportModule("sys"); string codeToRedirectOutput = "import sys\n" + "from io import StringIO\n" + "sys.stdout = mystdout = StringIO()\n" + "sys.stdout.flush()\n" + "sys.stderr = mystderr = StringIO()\n" + "sys.stderr.flush()\n"; PythonEngine.RunString(codeToRedirectOutput); // Run Python code string pyCode = "print(1 + 2)"; PyObject result = PythonEngine.RunString(pyCode); // null in case of error if (result != null) { string pyStdout = sys.stdout.getvalue(); // Get stdout pyStdout = pyStdout.Replace("\n", "\r\n"); // To support newline for textbox textBox1.Text = pyStdout; } else { PythonEngine.PrintError(); // Make Python engine print errors string pyStderr = sys.stderr.getvalue(); // Get stderr pyStderr = pyStderr.Replace("\n", "\r\n"); // To support newline for textbox textBox1.Text = pyStderr; } } }With this code, I was able to redirect the stdout (and stderr in the case of an error) from the Python engine to a .NET text box. On Wed, May 18, 2016 at 12:02 AM, Saparya K wrote: Hi Denis,Thanks for pointing me to the new API. I am now able to embed Python in my C# code and access Python classes and methods from C#! Hi Nils,Your application looks very interesting and some of the features (e.g. matplotlib integration) are on the lines of what I have been thinking about. I am far from there though and will need to learn more before I can follow all the code in your wrapper! - As of now, I am trying to redirect the output from the Python interpreter to a .NET text box. While I am able to redirect the output to a file, I am having trouble with routing the output to a text box. I first tried to redirect the console output to a custom TextWriter using Console.SetOut in C#: private void Form1_Load(object sender, EventArgs e){ _writer = new TextBoxWriter(this.textBox1); Console.SetOut(_writer); // Redirect stdout to custom TextWriter that writes to the text box} This did not work: while output from C# is routed to the text box, output from Python is not. - I then thought that maybe I need to redirect the Python stdout instead of the C# standard output. The idea was to assign Python's sys.stdout to a .NET object that implements the same interface as a python stream (write(), writelines()...): .NET class to mimic Python stream: -public class TextBoxStream : PyObject // To assign to sys.stdout. Is this correct? { private TextBox _output = null; public TextBoxStream() {} public TextBoxStream(TextBox output) { _output = output; } void write(object value) { _output.AppendText(value.ToString()); } }In Form1.cs: private void button1_Click(object sender, EventArgs e) { using (Py.GIL()) { // Redirect stdout to text box dynamic sys = PythonEngine.ImportModule("sys"); TextBoxStream textBoxStream = new TextBoxStream(textBox1); sys.stdout = textBoxStream; // This is probably not theright way? //sys.SetAttr("stdout", textBoxStream); // This did not work either string code = "import sys\n" + "print 'Message 1'\n" + "sys.stdout.write('Message 2')\n" + "sys.stdout.flush()"; PyObject redirectPyObj = PythonEngine.RunString(code); // returns NULL sys.stdout.write("Message 3"); // Exception thrown: 'Python.Runtime.PyObject' does not contain a definition for 'stdout' } } This does not work either: redirectPyObj is NULL. I tried using the old as well as the new Python.NET API (with dynamic). Neither the sys.stdout.write nor the print statements write to the text box.Any ideas on how to approach this would be very helpful.Thanks,Saparya On Tue, May 17, 2016 at 3:33 AM, Nils Becker wrote: Hey, a while ago I wrote something like a light wrapper around Python.NET to embed CPython with numpy/scipy in a .NET GUI. It manages local/global dictionaries, automatically converts simple data types and n
Re: [Python.NET] Embedded Python .Net example - running scripts
Did you try background or threadpool threads? Redirected process calls and looking for stdin stdout stderr streams allows more control. Sent from Yahoo Mail on Android On Wed, Oct 3, 2018 at 15:47, Luke, Steve wrote: I am getting a crash trying to embed Python into my VB program using Python for .NET. The goal of my application is to allow users to run their own python scripts inside a larger application. The crash I am getting happens the second time I run a script that imports certain large libraries (like numpy or scikit-image) but does not affect all libraries (for example PIL). My environment: Windows 10 Pro x64, Python 3.6.5 (in Anaconda), Python for .Net 2.4.0 (installed from git’s master branch). Here is the VB code: PublicFunction Startup(ByRef param AsString)AsInteger PythonEngine.Initialize() 'mm.PrintMsg(PythonEngine.BuildInfo) 'mm.PrintMsg(PythonEngine.Compiler) 'mm.PrintMsg(PythonEngine.Platform) 'mm.PrintMsg(PythonEngine.ProgramName) 'mm.PrintMsg(PythonEngine.PythonHome) 'mm.PrintMsg(PythonEngine.PythonPath) Using (Py.GIL()) Dim scriptPath AsString = param Dim scriptDir AsString = Path.GetDirectoryName(scriptPath) Dim scriptName AsString = GetPythonModuleName(scriptPath) Dim scriptParam AsString = "" Dim scriptScope As PyScope = Py.CreateScope() Dim scriptText AsString = My.Computer.FileSystem.ReadAllText(scriptPath) scriptScope.Exec(scriptText) If scriptScope.Contains(STARTUP_METHOD_NAME) Then scriptScope.Exec(String.Format("{0}(r'{1}')", STARTUP_METHOD_NAME, scriptParam)) EndIf scriptScope.Dispose() EndUsing PythonEngine.Shutdown() Return 0 EndFunction And this is the Python script I am running: import skimage.io defStartup(param): pass defDocommand(param): pass defShutdown(): pass When I run it the VB code the first time, things work great. When I run the VB code a second time (without first restarting the entire application) I get an access violation exception on the scriptScope.Exec() call: Exception: System.AccessViolationException : Message: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Source: Python.Runtime StackTrace: at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw) at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw) at Python.Runtime.Runtime.PyRun_String(String code, IntPtr st, IntPtr globals, IntPtr locals) at Python.Runtime.PyScope.Exec(String code, IntPtr _globals, IntPtr _locals) at MyApp.MyClass.Startup(String& param) in C:\Git\MyPath\MyApp.vb:line 132 Unfortunately the stack trace doesn't show line numbers for anything in the Python.Runtime. Interestingly, if you look at the VB code, I have some lines of commented out code: 'mm.PrintMsg(PythonEngine.BuildInfo) 'mm.PrintMsg(PythonEngine.Compiler) 'mm.PrintMsg(PythonEngine.Platform) 'mm.PrintMsg(PythonEngine.ProgramName) 'mm.PrintMsg(PythonEngine.PythonHome) 'mm.PrintMsg(PythonEngine.PythonPath) Since the app doesn’t have a console, this sends the text to the enclosing app for display. If I uncommon that code, then the first time I run it I get: default, Mar 29 2018, 13:32:41 [MSC v.1900 64 bit (AMD64)] win32 python F:\An