gpt4 book ai didi

c# - .Net : Running an embedded interpreter 的 Python

转载 作者:行者123 更新时间:2023-12-03 17:49:11 26 4
gpt4 key购买 nike

我正在尝试使用 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 发行版复制 DLLs 和 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也有所有这些错误。

知道我做错了什么吗?

最佳答案

VS 在路径中有 Python 文件夹,在 Vs 之外没有可以提供帮助的环境变量。关键是你必须在 PATH 中有 Python。
要深入了解,请参阅:https://github.com/pythonnet/pythonnet/issues/1301

关于c# - .Net : Running an embedded interpreter 的 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com