Python for .Net:运行嵌入式解释器

5 投票
1 回答
2273 浏览
提问于 2025-04-18 17:48

我正在尝试使用Python3.2,并且使用的是在这个链接找到的Python.Net版本:https://github.com/renshawbay/pythonnet

我用的是下面这个简单的测试程序:

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的错误信息。

你觉得我哪里做错了呢?

1 个回答

0

在VS(Visual Studio)中,有一个Python的文件夹在路径里,但在VS之外没有环境变量可以帮忙。关键是你必须确保Python在你的路径中。

想了解更多,可以看看这个链接: https://github.com/pythonnet/pythonnet/issues/1301

撰写回答