Skip to content
Advertisement

Python.net is not receiving correct encoded string from .net

I am using .net 4.7.1 console program talking to python.net that VS2017 is reporting as version 2.5.1.0 (runtime version v4.0.30319) Python code is in 3.6

python:

def ping(input):
    if (input == 'ping'):
        return 'pong'
    return 'invalid'

def headervalid(header):
    if (header == '@nu001erANSI '):
        return True
    return False

if __name__ == '__main__':
    input = '@nu001erANSI '
    print(headervalid(input))
    input = 'ping'
    print(ping(input))

dot net :

using (Py.GIL())
            {
                dynamic np = Py.Import("numpy");
                Console.WriteLine(np.cos(np.pi * 2));

                dynamic sin = np.sin;
                Console.WriteLine(sin(5));

                double c = np.cos(5) + sin(5);
                Console.WriteLine(c);

                dynamic a = np.array(new List<float> { 1, 2, 3 });
                Console.WriteLine(a.dtype);

                dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
                Console.WriteLine(b.dtype);

                Console.WriteLine(a * b);

                dynamic parsers = Py.Import("newworld_parsers.bridgetest");

                string input = "ping";
                var result = parsers.ping(input);
                Console.WriteLine(result);
                input = @"@nu001erANSI ";
                result = parsers.headervalid(input);
                Console.WriteLine(result);

                Console.WriteLine("=======");
                Console.ReadLine();
            }

The python stand alone run reports:

True
pong
Press any key to continue . . .

Dot net run reports:

1.0
-0.9589242746631385
-0.675262089199912
float64
int32
[ 6. 10. 12.]
pong
False
=== Press any key to continue ====

Notice the True in python vs the False when calling from C# The special characters in headervalid() from dot net don’t seem to be going over correctly. What should I do to fix this? Any ideas greatly appreciated!

Advertisement

Answer

Putting ‘@’ character in front of C# string turns it into a raw string, meaning no escape sequences inside will work.

You can see that by adding Console.WriteLine(input); to your code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement