I have a Python script which receives data from a .NET application. How do I use an incoming buffer of type 'System.Collections.Generic.List`1[System.Byte]' in my script?
The function of the script would be to find and replace string tokens, reassemble the buffer back into System.Collections.Generic.List`1[System.Byte] and then return the buffer back to a .NET server.
I am very new to Python. This is what I have so far:
import array
import clr
from System.Collections.Generic import *
def SetRecvBuffer(buffer):
li = List[byte](buffer)
hookme.Debug(li)
for x in li:
hookme.Debug(x)
Any help would be appreciated. Thanks!
The problem is that C# List initialization on Python side ignores the items given in brackets which looks like a bug, for now instead use List.Add():
import clr
clr.AddReference("System.Collections")
from System.Collections.Generic import List
from System import Int32
li = List[Int32](range(3))
list(li) #returns []
li.Add(5)
list(li) #returns [5]
Related
Does C# have a library that can reproduce the same thing?
from tensorflow import keras
from tensorflow.keras import layers
Functions to reproduce:
# A utility function to decode the output of the network
def decode_batch_predictions(pred):
input_len = np.ones(pred.shape[0]) * pred.shape[1]
# Use greedy search. For complex tasks, you can use beam search
results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][:, :max_length]
# Iterate over the results and get back the text
output_text = []
for res in results:
res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
output_text.append(res)
return output_text
The situation is as follows. I trained the model, it works fine. But I haven 't found a way to decode the model 's response in the environment yet .NET ;(
I will be grateful for any help.
I am trying to use Python.NET to perform interop between C# and Python on a Windows machine.
Specifically I have the following code.
PythonEngine.PythonHome = #"C:\Python\3_5_4";
PythonEngine.PythonPath = #"C:\Python\3_5_4\Lib;C:\Python\3_5_4\Lib\site-packages";
using (Python.Runtime.Py.GIL())
{
dynamic np = Py.Import("numpy");
dynamic sin = np.sin;
Console.WriteLine(sin);
}
While I can successfully execute a general python statement as such:
var res = PythonEngine.Eval("1 + 1");
Console.WriteLine(res);
//res = 2
Which indicates that the python engine itself is working successfully, I can also invoke something like this:
var html = Py.Import("html");
Console.WriteLine(html);
//html = <module 'html' from 'C:\\Python\\3_5_4\\Lib\\html\\__init__.py'>
Which further indicates that the module loading functionality is also working correctly.
However whenever I attempt to invoke the line:
dynamic np = Py.Import("numpy");
I receive the following error:
{"ImportError : No module named '_ctypes'"}.
[' File "C:\\Python\\3_5_4\\Lib\\site-packages\\numpy\\__init__.py", line 140, in <module>\n from . import _distributor_init\n', ' File "C:\\Python\\3_5_4\\Lib\\site-packages\\numpy\\_distributor_init.py", line 9, in <module>\n from ctypes import WinDLL\n', ' File "C:\\Python\\3_5_4\\Lib\\ctypes\\__init__.py", line 8, in <module>\n from _ctypes import Union, Structure, Array\n']
The file referenced is located # 'C:\Python\3_5_4\Lib\ctypes\__init__.py'.
I have verified that all the expected paths are set correctly and that the Ctypes folder exists in my python path.
I have tried everything from uninstalling and reinstalling Python to modifying the ctypes/__init__.py file to try and import Ctypes directly to no effect.
Having researched this topic online throughly I have found a number of suggestions which point to running yum install libffi-devel as detailed here. However this does not appear to be something that I can perform on windows given that yum appears to be a Linux only application.
Can anyone provide any guidance?
I want to get the code of a device from COM6, I easily get the output from C# using the code below:
serialPort1.Encoding = System.Text.Encoding.GetEncoding(28591);
but I don't know how to do it in Python.
I already tried:
import serial
import time
ser = serial.Serial()
ser.port='COM6'
ser.baudrate=9600
ser.parity=serial.PARITY_NONE
ser.stopbits=serial.STOPBITS_ONE
ser.bytesize=serial.EIGHTBITS
ser.timeout=2
if ser.is_open:
ser.close()
else:
ser.open()
print("connected to: " + ser.portstr)
while True:
ser.flushInput()
time.sleep(0.01)
data_raw = (ser.readline())
print(data_raw.decode("utf-8"))
You can use pythonnet to access .Net libraries. When I run the below code I get System.Text.Latin1Encoding
import clr
from System import Text
result = Text.Encoding.GetEncoding(28591)
print(result)
More here - https://github.com/pythonnet/pythonnet
I'm using ZeroMQ for inter-process communication between C# managed application and python script. When calling script from C#, using IronPython I get following error :
An unhandled exception of type
IronPython.Runtime.Exceptions.ImportException occurred in
Microsoft.Dynamic.dll
Additional information: cannot import constants from
zmq.backend.cython
Python code (test.py file):
import sys, zmq, time
def execute(input):
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://*:18800")
time.sleep(1)
publisher.send(input) #just echo input parameter
And this is how I execute .py code from my C# app :
static void Main(string[] args)
{
var options = new Dictionary<string, object>();
options["Frames"] = true;
options["FullFrames"] = true;
ScriptEngine _engine = Python.CreateEngine(options);
ScriptRuntime _runtime = _engine.Runtime;
ICollection<string> _searchPaths = _engine.GetSearchPaths();
_searchPaths.Add(#"C:\Python27\");
_searchPaths.Add(#"C:\Python27\Lib\");
_searchPaths.Add(#"C:\Python27\Scripts\");
_searchPaths.Add(#"C:\Python27\libs\");
_searchPaths.Add(#"C:\Python27\DLLs\");
_searchPaths.Add(#"C:\Python27\include\");
_searchPaths.Add(#"C:\Python27\lib\site-packages");
_engine.SetSearchPaths(_searchPaths);
dynamic wrapperObj = _runtime.UseFile("test.py");
wrapperObj.execute("test");
}
Note that some code is omitted for brevity, and not actually relevant for this scenario. When manually invoking .py script through the command line, everything works fine, I'm able to pass data around and my C# app is receiving messages.
Anyone knows what is this error and how can be solved?
EDIT : While I was desperate and almost gave up, I tried to write quick named-pipes support, and guess what - similar error:
An unhandled exception of type IronPython.Runtime.Exceptions.ImportException occurred in
Microsoft.Dynamic.dll
Additional information: No module named win32file
This time, my test.py looks like this:
import win32file
def execute(input):
handle = win32file.CreateFile(r"\\.\pipe\test_pipe",
win32file.GENERIC_WRITE,
0, None,
win32file.OPEN_EXISTING,
0, None)
if handle:
win32file.WriteFile(self.handle, input, None)
win32file.FlushFileBuffers(self.handle)
win32file.SetFilePointer(self.handle, 0, win32file.FILE_BEGIN)
I'm not really sure if I have more options for this kind of interoperability, but I'm starting to think that IronPython can just cover basic usage scenarios (when calling pure python code from C#), not to mention matplotlib, numpy or astropy that I will certanly need later on.
Thanks in advance!
Regards,
Civa
I'm wondering if there is a possibility to call a specific Method from a Python script over a C# project.
I have no code... but my idea is:
Python Code:
def SetHostInfos(Host,IP,Password):
Work to do...
def CalcAdd(Numb1,Numb2):
Work to do...
C# Code:
SetHostInfos("test","0.0.0.0","PWD")
result = CalcAdd(12,13)
How can I call one of the Methods, from this Python script, over C#?
You can host IronPython, execute the script and access the functions defined within the script through the created scope.
The following sample shows the basic concept and two ways of using the function from C#.
var pySrc =
#"def CalcAdd(Numb1, Numb2):
return Numb1 + Numb2";
// host python and execute script
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pySrc, scope);
// get function and dynamically invoke
var calcAdd = scope.GetVariable("CalcAdd");
var result = calcAdd(34, 8); // returns 42 (Int32)
// get function with a strongly typed signature
var calcAddTyped = scope.GetVariable<Func<decimal, decimal, decimal>>("CalcAdd");
var resultTyped = calcAddTyped(5, 7); // returns 12m
I found a similar way to do it, the call of the method is much easier with it.
C# Code goes as follows:
IDictionary<string, object> options = new Dictionary<string, object>();
options["Arguments"] = new [] {"C:\Program Files (x86)\IronPython 2.7\Lib", "bar"};
var ipy = Python.CreateRuntime(options);
dynamic Python_File = ipy.UseFile("test.py");
Python_File.MethodCall("test");
So basically I submit the Dictionary with the Library path which I want to define in my python file.
So the PYthon Script looks as follows:
#!/usr/bin/python
import sys
path = sys.argv[0] #1 argument given is a string for the path
sys.path.append(path)
import httplib
import urllib
import string
def MethodCall(OutputString):
print Outputstring
So The method call is now much easier from C#
And the argument passing stays the same.
Also with this code you are able to get a custom library folder
for the Python file which is very nice if you work in a network
with a lot of different PC's
You could make your python program take arguments on the command line then call it as a command line app from your C# code.
If that's the way to go then there are plenty of resources:
How do I run a Python script from C#?
http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-a-c-4-0-program.aspx