The Wayback Machine - https://web.archive.org/web/20221002194926/https://gitter.im/pythonnet/pythonnet

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 17:46
    mpottinger starred pythonnet/pythonnet
  • Oct 01 18:22
    dnfadmin commented #1275
  • Oct 01 17:58
    dnfadmin commented #1208
  • Oct 01 16:34
    dbarU starred pythonnet/pythonnet
  • Oct 01 03:48
    lostmsu commented #1958
  • Oct 01 03:46
    lostmsu commented #1958
  • Oct 01 03:44
    lostmsu commented #1958
  • Sep 30 22:16
    spex66 starred pythonnet/pythonnet
  • Sep 30 20:44
    filmor commented #1958
  • Sep 30 18:35

    lostmsu on alpha2

    (compare)

  • Sep 30 18:35

    lostmsu on alpha1

    (compare)

  • Sep 30 18:34
    lostmsu commented #1958
  • Sep 30 18:28
    lostmsu review_requested #1958
  • Sep 30 18:21
    lostmsu opened #1958
  • Sep 30 17:58
    lostmsu opened #1957
  • Sep 30 14:40
    murilo-cunha starred pythonnet/pythonnet
  • Sep 30 13:13
    orvly starred pythonnet/pythonnet
  • Sep 30 08:44
    dnfadmin commented #1467
  • Sep 30 07:07
    jalew188 starred pythonnet/pythonnet
  • Sep 30 04:59
    brettvitaz starred pythonnet/pythonnet
Oba Tochukwu
@torch016
@3x0dv5 did you find a solution to : Hi guys, trying to use pythonnet from a dotnet core 3.1 on Linux, I want to be able to execute Python from within C# code. Before I go down in a rabbit hole I would like to know if this is even possible. Do you guys know if it is possible to execute python3.7 code from .netcore 3.1 code under Linux?
pie_
@jcie74:matrix.org
[m]
Hi folks
I'm trying to instantiate this: public static class EntityManager<T> where T : EntityBase, new()
What am I doing wrong?:
>>> dc = {x.Name:x for x in asm.DefinedTypes}
>>> dc['EntityManager'][dc['AnEntity']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unindexable object
pie_
@jcie74:matrix.org
[m]
Ok, the problem was that this is the access method where I need to use the `1 suffix.
I can at least use .MakeGenericType now.
annpeter
@annpeter
I want to know how can i change the virtual env after I set the env before.
MajorIsato
@MajorIsato
How can I unload or overload the dll file that is loaded by clr.AddReference? Because there is some serious memory leaks during I load dll in a loop using pythonnet, so I want to unload my dll after per loop is finished.
`clr.AddReference('ThermoFisher.CommonCore.Data')
from ThermoFisher.CommonCore.Data.Interfaces import IChromatogramSettings, IScanEventBase, IScanFilter, RawFileClassification
def ReadScanInformation(ms_file, mzToSearch, tolerance=40):
"""Reads the general scan information for each scan in the RAW file
using the scan filter object and also the trailer extra data
section for that same scan.
Args:
    rawFile (IRawDataPlus): the RAW file being read.
    mzToSearch (list): the output data flag.
    tolerance (int): tolerance of mass matching.
"""
rawFile = RawFileReaderAdapter.FileFactory(ms_file)
# set the selected instrument to the MS instrument, first instance of it
rawFile.SelectInstrument(Device.MS, 1)
result = []
firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum
lastScanNumber = rawFile.RunHeaderEx.LastSpectrum
# Read each scan in the RAW File
objgraph.show_growth()
for scan in range(firstScanNumber, lastScanNumber):
    if scan % 100 == 0:
        objgraph.show_growth()
        print(1)
    # Get the retention time for this scan number.  This is one of
    # two comparable functions that will convert between retention
    # time and scan number.
    print(scan)
    time = rawFile.RetentionTimeFromScanNumber(scan)

    # Get the scan filter for this scan number
    scanFilter = IScanFilter(rawFile.GetFilterForScanNumber(scan))

    # Get the scan event for this scan number
    scanEvent = IScanEventBase(rawFile.GetScanEventForScanNumber(scan))`
memory keeps increasing once one loop is finished
MajorIsato
@MajorIsato
thx
rkaluvala2504
@rkaluvala2504
Hi I built a library in C# in .NET core that connects to Sql Server for fetching the data. I am building a Python wrapper using pythonnet and loaded the dll. But when I tried calling the method, I am getting a Null Reference Exception at conn.CreateCommand().. The C# code works fine. Did anyone faced similar issues?
3 replies
jhe-pf
@jhe-pf
Hello everybody, is there an overview which Python and which .net-Versions are supported? I am using Python 3.8.5 (and also tried 3.9.10) on Windows 10. I am using a .NET-DLL which was upgraded from .net 4.x to .net 6. So I upgraded from pythonnet 2.5.x to 3.0.0rc2. I adapted the loading of the clr-stuff to the getcore-clr with app.runtime.json-description scheme. Everything went extremely smooth. Except for one tiny detail: It happens that I cannot call the cunstroctor of an System.IntPtr. dest_pointer = IntPtr.OverloadsInt64 throws an exception: "TypeError: No match found for given type params": Even the example from the pythonnet homepage (s = String.OverloadsChar, Int32 ) throws the same exception. So my question is. Am I missing something? Btw: I found a simple, yet ugly workaround: dest_pointer = IntPtr.Parse(str(p)). Thank you for your help.
jhe-pf
@jhe-pf
dest_pointer = IntPtr.__overloads__[Int64](p)
Traceback (most recent call last):
  File "C:\Python\WinPython-64bit-3.8.5.0\python-3.8.5.amd64\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: No match found for given type params

is the error I get. Also:

s = String.Overloads[Char, Int32]('A', 10)
Traceback (most recent call last):
  File "C:\tools\python3\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: No match found for given type params

Workaround:

dest_pointer = IntPtr.Parse(str(p))
9 replies
audacode
@audacode
Has anyone got pythonnet 3 rc working with .NET 5 or 6 (on Linux)? If so, does anyone know of any write up, blog post, or video that explains how to set this up? I have spent about an hour looking but cannot find any information (other than old .NET Framework instructions).
johnW_ret
@johnW-ret
Hey, I've had this issue for a while but I just found this chat room. Anyone tried running the Python runtime in .NET on ARM64?
johnW_ret
@johnW-ret
Update: I specifically meant on Windows. I usually don't ask the internet until I feel I'm at my wit's end, but it turns out that I always figure it out right after I ask. Executable was ARM64 and I was trying to load an x64 dll.
Zachary Munro
@zmunro
How would I go about debugging an issue where as soon as I import a dll I, the python interpreter crashes? I am trying to import this DLL: https://github.com/PNNL-Comp-Mass-Spec/Informed-Proteomics/blob/master/lib/ThermoFisher.CommonCore.Data.dll
But after I add it as a reference and try to import it, the python interpreter crashes:
Python 3.7.11 (default, Sep  3 2021, 06:28:51) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> clr.AddReference("ThermoFisher.CommonCore.Data.dll")
<System.Reflection.MonoAssembly object at 0xffff7bf98210>
>>> import ThermoFisher.CommonCore.Data.Business as Business

=================================================================
        Native Crash Reporting
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================
/proc/self/maps:
aaaaab010000-aaaaab011000 r-xp 00000000 fe:01 542298                     /usr/local/bin/python3.7
aaaaab020000-aaaaab021000 r--p 00000000 fe:01 542298                     /usr/local/bin/python3.7
aaaaab021000-aaaaab022000 rw-p 00001000 fe:01 542298                     /usr/local/bin/python3.7
...
=================================================================
        Basic Fault Adddress Reporting
=================================================================
instruction pointer is NULL, skip dumping
=================================================================
        Native stacktrace:
=================================================================
        0xffff83020ca8 - /usr/lib/libmonosgen-2.0.so.1 : (null)
=================================================================
        Telemetry Dumper:
=================================================================
Pkilling 0xffff8048b1e0 from 0xffff8370b010
Entering thread summarizer pause from 0xffff8370b010
Finished thread summarizer pause from 0xffff8370b010.
Waiting for dumping threads to resume
Debug info from gdb:
=================================================================
        External Debugger Dump:
=================================================================
mono_gdb_render_native_backtraces not supported on this platform, unable to find gdb or lldb
=================================================================
        Managed Stacktrace:
=================================================================
          at <unknown> <0xffffffff>
          at Python.Runtime.Runtime:PyType_Ready <0x00007>
          at Python.Runtime.TypeManager:CreateType <0x004d3>
          at Python.Runtime.TypeManager:GetTypeHandle <0x00063>
          at Python.Runtime.ClassManager:InitClassBase <0x0006b>
          at Python.Runtime.ClassManager:GetClass <0x00087>
          at Python.Runtime.ModuleObject:GetAttribute <0x0021f>
          at Python.Runtime.ModuleObject:GetAttribute <0x00447>
          at Python.Runtime.ModuleObject:LoadNames <0x00097>
          at Python.Runtime.ImportHook:__import__ <0x0072f>
          at Python.Runtime.ImportHook:__import__ <0x0005b>
=================================================================
Aborted
Zachary Munro
@zmunro
Is this room not active anymore? I have been asking questions for a few days without response
MaxCatani1967
@MaxCatani1967
Bye
ArjunWhabi
@ArjunWhabi

Hello, I have written the following Console APP and it runs perfecty fine :
Class.cs file is below
'''
using Python.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TestProject2
{

public class PythonInterop
{
    public static void Initialize()
    {

        string pythonDll = @"C:\Python36\python36.dll";
        Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", pythonDll);

        var pythonPath = @"C:\Python36\";


        //Solution as per my console program
        Environment.SetEnvironmentVariable("PATH", $@"{pythonPath};" + Environment.GetEnvironmentVariable("PATH"));
        Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath);
        Environment.SetEnvironmentVariable("PYTHONPATH ", $@"{pythonPath}\Lib");
        PythonEngine.Initialize();
  }
    public static object RunPythonCode_Many_Params(string pycode, List<object> parameters, List<string> parameterNames, string returnedVariableName)
    {   
        // Create Your lists of Paramter Inputs and Paramter String Names
        //var parameters = new List<object> { x, NumFeatures };
        //var parameterNames = new List<string> { "x", "NumFeatures" };

        object returnedVariable = new object();
        Initialize();
        using (Py.GIL())
        {
            using (PyScope scope = Py.CreateScope())
            {

                var parametersParamtersNames = parameters.Zip(parameterNames, (p, pn) => new { Param = p, ParamName = pn });

                foreach (var ppn in parametersParamtersNames)
                {
                    scope.Set(ppn.ParamName, ppn.Param.ToPython());

                    //Console.WriteLine(ppn.Param+ "   "+ ppn.ParamName);
                    //Console.WriteLine(ppn.Param.GetType() + "   " + ppn.ParamName.GetType());
                }
                scope.Exec(pycode);
                returnedVariable = scope.Get<object>(returnedVariableName);                   
            }

        }

        return returnedVariable;
    }

    public static object CompileandRun(object parameter, string parameterName, object parameter2, string parameterName2 , string filelocation,string functionname)
    {
        object returnedVariable = new object();
        Initialize();
        using (Py.GIL())
        {
            using (PyScope scope = Py.CreateScope())
            {

                scope.Set(parameterName , parameter.ToPython());
                scope.Set(parameterName2, parameter2.ToPython());

                string code = File.ReadAllText(filelocation);

                var scriptCompiled = PythonEngine.Compile(code);

                scope.Execute(scriptCompiled);

                dynamic func = scope.Get(functionname);
                returnedVariable = func(parameter, parameter2);

            }

        }
        return returnedVariable;
    }
}

}

'''

Hi Could anyone please guide me ? any help would be highly appreciated?

Iván Jiménez
@ivanjimenez

Hi, Folks from Pythonnet: I have a simple api in C# in dll file to use a device. I can communicate with the device with Pythonnet (clr) using dll in ipython terminal with no problem. But when I run the script: python script.py it stops with exit 0 and breaks the execution. I have issolated the error in a function with one string argument. But the code still works in ipython. I put the example code:

clr.AddReference("SensorSDK")

from SensorSDK import Sensor, SensorData, Device

api = Sensor()
data = SensorData()
error = ""                                                                                                                                                                                                               
 def Api_dataReceived(deviceHandler : bytes, data : SensorData): 
        # get data from attributes

# publish the callback (it's right?)

api.dataReceived += Api_dataReceived


api.Open("COM1", error)

# Method to configure the sensor
api.SetDevicesConfigurations(111,2222,error)


# Method to start communication to get values from sensor
api.StartStream("None") # Here fails with python script.py but it works in ipython

# The header of StarStream in C Sharp is

  public bool StartStream(out string error)
        {
            error = "";

            [making things]

            return true;
        }

#

This simple script works in ipython properly but it does not work calling the script with python.
I appreciate some hint about what it happens.
Thanks

stellarpower
@stellarpower
Could someone let me know what the correct way is to use pythonnet with a conda/mamba/micrommaba environment please? I have tried the variety of snippets on the wiki and in the issues, so far ot no avail. It's not clear ot me what paths need to be provided where nor at what point the process is really failing. I get an error about failing to load symbols, but readelf shows them as present, so it must be a path issue, but at what point it has failed I do not know. Thanks
stellarpower
@stellarpower
Okay, for reference, nothing messing with PYTHONPATH or any other environment variables worked.
static void Main(string[] args ){
        Runtime.PythonDLL = "/root/micromamba/lib/libpython3.so";

        // Don't forget this! Or it'll just pass through silently.
        PythonEngine.Initialize(new List<String>());

        using (Py.GIL()){ // Global Interpreter Lock

            using (var scope = Py.CreateScope()){

                scope.Exec("print(\"hi\")");

            }

        }
    }
was the simple slution
heartacker
@heartacker
image.png
hi, can anybody help me? I do not know how to convert a list (from python code, which is list[int]) to c# list<int> or array[int]. please
image.png
stellarpower
@stellarpower
I don;t know much about .net, but I imaging you might want to use IEnumerable.
Quite possibly it isn;t strictly a List but implements the interface for iteration
Hieutrinh1505
@Hieutrinh1505
image.png
image.png
how can I pass a c# function to python, especially when I use scipy package ?
Hemanshu Authankar
@hemanshupa
Hi everyone, is pythonnet is supported on Linux using .net framework from Microsoft instead of Mono libraries which seems to be deprecated?
tuhe
@tuhe
image.png
I have encountered a problem where I can load some DLL files from a project but not others. The screenshot shows the two DLL files I can load and the final file (YAFCparser.dll) which fails. This is using python 3.6. I can recompile the DLL files locally. The source code for the offending file is available here: https://github.com/ShadowTheAge/yafc/blob/master/YAFCparser/FactorioDataSource.cs . I wonder if anyone have an idea what the problem might be and if it is fixable?
Paul Cresswell
@Pcres91
Hi all. Is 3.0.0 scheduled to work for Python versions 3.9 and up? I've been testing it on a 3.9 version, and I've had some things not work as expected.
Russel Webber
@RusselWebber
Hi, is it possible to reload a Python module from c#? I ended up with PythonEngine.Exec($"import importlib,{modName};importlib.reload({modName})"); Is there a more elegant solution? PyModule has a Reload method, but you can't create a PyModule instance from an existing module. Thanks
JH104779
@JH104779
I'm building c# app to run on Ubuntu. I'm calling Py.Import("numpy") - works fine on Windows - Does not locate "numpy" on Linux - numpy is installed on the Ubuntu box
DynaBimm
@DynaBimm
Hello everyone! Is it possible to use LINQ with latest version of Pythonnet? (need solution in Python) Thanks!
Yao-DY
@Yao-DY
Hi all. I have a C# dll, which have a class with a property represents a vector with two dimensions, how can I get the vector in python? I tried to get it as "a.b", but when i print it, I just print "System.Single[,]". Thanks
Collin Dekorne
@CollindeKorne
Hello all, I am trying to use a C# library using pythonnet and am getting a "Process is terminated due to StackOverflowException." error. Does anyone have any advice on how to get more information from this error? Thank you in advance.
AbdalaMask
@AbdalaMask
hi
how using code python to
@jit(nopython=True)
def get_white_blue(image, aux):
h = image.shape[0]; w = image.shape[1]
white = 200; local_thre = 30; global_thre = 60

# loop over the image, pixel by pixel
for y in range(0, h):
    for x in range(0, w):
        b,g,r = image[y,x]

        s,m,l = np.sort(image[y,x])

        local_dis = (m-l)*(m-l)+(m-s)*(m-s)
        aux[y, x, 0] = 1 if (local_dis<local_thre*local_thre and abs(white-(s+m+l)/3)<global_thre) else 0
        aux[y, x, 1] = 1 if (s==r and l==b and r<100 and b>120 and b-g>20 and b-g<110) else 0
how using code python to pythonnet

import cv2 as cv
import numpy as np
import numba
from numba import jit
from commonfunctions import
from tkinter import

@jit(nopython=True)
def get_white_blue(image, aux):

h = image.shape[0]; w = image.shape[1]
white = 200; local_thre = 30; global_thre = 60

# loop over the image, pixel by pixel
for y in range(0, h):
    for x in range(0, w):
        b,g,r = image[y,x]

        s,m,l = np.sort(image[y,x])

        local_dis = (m-l)*(m-l)+(m-s)*(m-s)
        aux[y, x, 0] = 1 if (local_dis<local_thre*local_thre and abs(white-(s+m+l)/3)<global_thre) else 0
        aux[y, x, 1] = 1 if (s==r and l==b and r<100 and b>120 and b-g>20 and b-g<110) else 0
Welcome
Can you help me convert this project to c-sharp?
Program in Python language
Please help me convert it to c-sharp
ranjithspandana
@ranjithspandana
Hi all I recently updated pythonnet to latest version i.e. 3.0.0.post1. I have a library built using .NET CORE 3.0. I imported the C# library and followed the steps i.e. load(''coreclr"). Importing the DLL works, but when I call a method that is connecting to SQL Server and fetches the data. I am getting the following error i.e. Could not load file or assembly Microsoft.Data.SqlClient Version=4.1.0.0. The C# Library works fine when I tested with a Console Application. Anyone faced File Not Found Exception after importing into python. Any help is appreciated.
_