IronPython error under .Net Core: "failed to parse CPython sys:version"

Question:

I have a .Net 4.x WPF desktop solution that uses IronPython to run numerous scripts in the form of .py files. I’ve just finished migrating the solution to .Net 6, but I see this error when the software tries to run a particular script:

IronPython.Runtime.Exceptions.ValueErrorException: ‘failed to parse CPython sys.version: ‘2.7.12 (2.7.12.1000)n[.NETCoreApp,Version=v3.1 on .NET 6.0.6 (64-bit)]”

The .py file that fails simply displays the Python version:

import platform

...

print 'Using Python {0}'.format(platform.python_version())

How can I resolve this problem? Modifying the .py file is out of the question (at this stage), as we have a large customer base, all with the same script installed on their PCs.

Asked By: Andrew Stephens

||

Answers:

I’ve found one solution, which is to execute the following script after creating the ScriptEngine object, to replace the version with a hardcoded string:

_scriptEngine.Execute(@"
import sys
version_bak = sys.version
sys.version = '2.7.12 (IronPython 2.7.12 (2.7.12.1000) on .NET 
6.0.0.0 (64-bit))'
import platform
platform.python_implementation()
platform._sys_version_cache[version_bak] = 
platform._sys_version_cache[sys.version]
sys.version = version_bak
");

This works, and I can further refine it to use the correct IronPython and .Net version no.s rather than hardcode those. Just wondering if there is a better solution out there though, such as manipulating the version number via IronPython classes rather than have to run this script each time?

Answered By: Andrew Stephens

I’ve discovered an easier way to change the version string is as follows that doesn’t involve running a script as per my other answer:

_scriptEngine.Runtime.SetHostVariables(
    "", 
    "", 
    "2.7.12 (IronPython 2.7.12 (2.7.12.1000) on .NET 6.0.0.0 (64-bit))");

The hardcoded string can be refined by dropping in the current IronPython and .Net versions like so:

var ironPythonVer = _engine.LanguageVersion;
var netVer = Environment.Version;
_scriptEngine.Runtime.SetHostVariables(
    "", 
    "", 
    "{ironPythonVer} (IronPython {ironPythonVer} ({ironPythonVer}.0) on .NET {netVer} (64-bit))");
Answered By: Andrew Stephens
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.