Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 03:09
    CRC42 starred pythonnet/pythonnet
  • 03:06
    lostmsu commented #1913
  • 03:05
    lostmsu commented #1913
  • 02:52
    lostmsu commented #1908
  • 02:52
    lostmsu commented #1908
  • 02:51
    lostmsu commented #1908
  • 02:44
    lostmsu commented #1914
  • Aug 15 22:49
    lostmsu commented #1754
  • Aug 15 20:22
    filmor closed #1915
  • Aug 15 20:22
    filmor locked #1915
  • Aug 15 18:42
    aztecboy opened #1915
  • Aug 15 18:06
    koubaa edited #1914
  • Aug 15 18:05
    koubaa edited #1914
  • Aug 15 18:04
    koubaa edited #1914
  • Aug 15 18:04
    koubaa opened #1914
  • Aug 15 14:42
    Pcres91 edited #1913
  • Aug 15 14:41
    filmor commented #1908
  • Aug 15 14:38
    Pcres91 edited #1913
  • Aug 15 14:31
    Pcres91 opened #1913
  • Aug 15 13:45
    zhawkins-viasat commented #1754
luky92
@luky92:matrix.org
[m]
how do i import a custom module that isn't in the same folder as main exe do I do just folderName.ModuleName like in python?
Jhonathan Abreu
@jhonabreul

Hello everyone, quick question: in Python code, is there a way to pass a Python dict to a C# method that takes an IDictionary<key_type, value_type>?

I think it was not supported, but this is from 2008. Perhaps it is supported now somehow? https://mail.python.org/pipermail/pythondotnet/2008-June/000819.html

cgeorcelin
@cgeorcelin
image.png
Has anybody been successful in referencing Autocad dll's?
like-magic
@like-magic
Hi, nob to python and trying to get pythonnet running on py3.10. downloaded pythonnet from github. it is an isolated machine so had to comment out nuget and manual download & install dependances (add cffi, urllib3, clrloader, requests, clr_loader, codecov, coverage, idna, setuptools, wheel ).
manifest.in had warning about first line removed the trailing back slash off src
setup.py at line 138 added name = 'pythonnet', version = '3.0.0-dev1'
py setup.py install
still can not import clr in python project - what is next step?
Arash Aghlara
@aghlara_twitter
Just wanted to say "pythonnet" is awesome, thanks every one!
any timeframe for the final 3.0 version?
Oba Tochukwu
@torch016
Hi guys. I would like to ask if ppthonet can read a module in a DLL built suing .netcore v3.1
Michael A.
@m-ad
image.png
Hello, i am struggling with a function that has a ref array of int argument. I know that I need to provide it with a dummy value [0]. The call goes thorugh fine. But the return value is not a list/array of integers but just an integer.
In python I call x = USB2_getModuleConnectionList([0], 0). Then I get (0, 1) back. 0 is the status return value, which tells me the call went okay. The 1 is of type int, but I would expect it to be a list. What am I doing wrong here?
system: pythonnet 2.5.2, python 3.8, win10 x64
Michael A.
@m-ad
Thanks in advance if anybody can give me some hints!
Michael A.
@m-ad

I also tried it with IronPythons clr.Reference method:

ref =  clr.Reference[System.Array[System.Int16]]()
print(ref)
self.lib.USB2_getModuleConnectionList(ref, 0)
print(ref)

but this results in a TypeError: expected Array[Int16], got StrongBox[Array[Int16]]

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?
1 reply
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.