-->

Python for .Net: Running an embedded interpreter

2019-04-10 19:04发布

问题:

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

I’m 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 a folder where I’ve copied the DLLs and Lib folder from a python 3.2 x86 distribution.

When I run it from Visual Studio it works fine (I guess it may be related to the fact that I’m using python tools for Visual Studio).

But when I run it from the console, it fails 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

The “print(a.Location);" works but not the “from System import Environment”. There are also all these errors about mbcs.

Any idea on what I’m doing wrong?