从C#调用Python脚本遇‘获取Python编解码器失败’致命错误的解决方法
C# Process调用Python 3.10脚本触发编码初始化致命错误
问题场景
通过C#的Process类调用本地Python 3.10脚本,脚本单独运行正常,但C#调用时出现Python编码相关的致命错误,无法正常执行。
相关代码
C#调用代码
static string CallPython(string fileName) { Process p = new Process(); p.StartInfo = new ProcessStartInfo(@"C:\Python310\python.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:\Python310\python.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:\Python310\lib\encodings\__init__.py", line 33, in <module> ImportError: cannot import name 'aliases' from partially initialized module 'encodings' (most likely due to a circular import) (C:\Python310\lib\encodings\__init__.py) 'PythonCallExperiment.exe' (CLR v4.0.30319: PythonCallExperiment.exe): Loaded 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PrivateAssemblies\Runtime\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
已尝试操作
- 将
UseShellExecute设置为true,问题未解决 - 搜索类似错误未找到有效方案
- 因VDI环境权限限制,暂未尝试IronPython
可行解决方案
方案1:显式设置PYTHONHOME环境变量
修改C#代码,在启动Python进程时添加PYTHONHOME环境变量,指向Python安装目录,帮助Python正确定位核心模块:
static string CallPython(string fileName) { Process p = new Process(); var startInfo = new ProcessStartInfo(@"C:\Python310\python.exe", fileName) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; // 添加PYTHONHOME环境变量 startInfo.EnvironmentVariables["PYTHONHOME"] = @"C:\Python310"; p.StartInfo = startInfo; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); return output; }
方案2:修正Python脚本的大小写问题
Python是大小写敏感语言,Print需改为小写的print(若用户实际脚本为笔误):
print("It worked?")
方案3:确认Python目录访问权限
在VDI环境中,确保C#进程拥有访问C:\Python310目录及其子目录(尤其是lib\encodings)的权限,避免因权限不足导致无法读取编码模块文件。
内容的提问来源于stack exchange,提问作者MNagy
相关产品推荐
相关产品推荐

