Python for .Net: running the built-in interpreter

I am trying to use Python3.2 using the Python.Net version found at: https://github.com/renshawbay/pythonnet

Im using the following simple test program:

using System;
using System.IO;
using Python.Runtime;

namespace TestPythonNet
{
    class Program
    {
        static void Main(string[] args)
        {
            string binDir = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).Location);
            string pyHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
            PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
            PythonEngine.ProgramName = "PythonRuntime";
            Environment.SetEnvironmentVariable("PYTHONPATH",
                Path.GetFullPath(Path.Combine(pyHome, "DLLs")) + ";" +
                Path.GetFullPath(Path.Combine(pyHome, "Lib")) + ";" +
                Path.GetFullPath(Path.Combine(pyHome, "Lib", "site-packages")) + ";" +
                binDir
                );
            Environment.SetEnvironmentVariable("PYTHONVERBOSE", "1");
            PythonEngine.Initialize();
            PythonEngine.ImportModule("clr");
            using (Py.GIL())
            {
                PythonEngine.RunSimpleString(
                    "import clr; " +
                   "a = clr.AddReference('System'); " +
                    "print(a.Location);" +
                    "from System import Environment;" +
                    "print(Environment.MachineName);");
            }
        }
    }
}

      

"D: \ src \ scratch \ TestPythonNet \ TestPythonNet \ PythonRuntime" is the folder where Ive copied the DLLs and Libs from the python 3.2 x86 distribution.

When I run it from Visual Studio it works fine (I think it might be because I'm using the Visual Studio python tools).

But when I run it from the console it doesn't work with the output:

Traceback (most recent call last):
  File "D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime\Lib\site.py", line 481, in execsitecustomize
    import sitecustomize
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
Traceback (most recent call last):
  File "D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime\Lib\site.py", line 497, in execusercustomize
    import usercustomize
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

      

"print (a.Location)"; works, but not "from the system import environment". There are also all these errors about mbcs.

Any idea on what I am doing wrong?

+4


source to share





All Articles