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
public static class EntityManager<T> where T : EntityBase, new()
>>> 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
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))`
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))
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
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?
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
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