我将使用在https://github.com/renshawbay/pythonnet找到的Python.Net版本来使用Python3.2。下面是一个简单的测试程序:
"
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” 是一个文件夹,我从 Python 3.2 x86 发行版中复制了 DLL 和 Lib 文件夹。
在 Visual Studio 中运行该程序时,它可以正常工作(我猜这可能与我正在使用 Visual Studio 的 Python 工具有关)。
但是,当我从控制台运行它时,它会失败并输出以下内容:
"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);"可以工作,但“from System import Environment”无法工作。同时还有一些关于mbcs的错误。
您对我做错了什么有任何想法吗?