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

时间:2014-08-19 14:32:45

标签: c# python .net python-3.x python.net

我正在尝试使用Python.Net版本使用Python3.2: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);&#34; 有效,但”来自系统导入环境“。还有关于mbcs的所有这些错误。

对我做错了什么的想法?

1 个答案:

答案 0 :(得分:0)

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