尝试从 C# 调用简单的 Python 脚本,但由于"无法获取 Python 编解码器"致命错误而失败。我该如何解决这个问题?



相关c#代码片段如下:

static string CallPython(string fileName)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:Python310python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}

和相关的Python脚本,其整体为:

Print("It worked?")

不幸的是,我没有得到想要的结果,而是从我的调试输出中得到以下结果:

Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'C:Python310python.exe'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'C:\Python310\python.exe'
sys.base_prefix = 'C:\Python310'
sys.base_exec_prefix = 'C:\Python310'
sys.platlibdir = 'lib'
sys.executable = 'C:\Python310\python.exe'
sys.prefix = 'C:\Python310'
sys.exec_prefix = 'C:\Python310'
sys.path = [
'C:\Python310\python310.zip',
'C:\Python310\DLLs',
'C:\Python310\lib',
'C:\Python310',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
Traceback (most recent call last):
File "C:Python310libencodings__init__.py", line 33, in <module>
ImportError: cannot import name 'aliases' from partially initialized module 'encodings' (most likely due to a circular import) (C:Python310libencodings__init__.py)
'PythonCallExperiment.exe' (CLR v4.0.30319: PythonCallExperiment.exe): Loaded 'C:Program Files (x86)Microsoft Visual Studio2017ProfessionalCommon7IDEPrivateAssembliesRuntimeMicrosoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

我尝试将UseShellExecute设置为true(否)。

对类似错误的其他搜索返回的结果似乎与我无关(例如手动设置PYTHONPATH)。有问题的脚本可以很容易地在这个实验之外运行(因此我怀疑我的Python 3.10安装可能并不困难)。我要提到的一个特点是,因为我不知道相关性,我试图在VDI上做到这一点(我经常遇到缺乏其他许多事情的管理访问权限的问题,这可能是这里的问题吗?)。

我还没有尝试用IronPython做同样的事情,因为我希望能够通过尽可能少地麻烦devOPS来重复地完成这个任务,但如果在这里没有什么可以为我做的,那就在未来的谈判桌上。

我想分享我的解决方案,它在我的一个项目中成功地工作了。

static string CallPython(string inputText)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
FileName = "C:\Python310\python.exe",
Arguments = "C:\myPyscripts\translateEng.py --text ""+inputText + "\" ,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}

最新更新