pythonnet / pythonnet/pythonnet

SerializationException when PythonEngine.Shutdown()

Open
#2,221 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
5.5k
Forks
780
PR merge metrics
No merged PRs in 30d

Description

Environment
  • Pythonnet version: 3.0.1
  • Python version: 3.8
  • Operating System: win11
  • .NET Runtime: 4.6.1
Details
  • Describe what you were trying to get done.

    my python code listed as following:

import datetime
import csv
import clr
clr.AddReference('CyberStone.Atp.Storage')
from CyberStone.Atp.Storage.Query import QueryCondition
from CyberStone.Atp.Modules.Analysis.Models import SearchResModel
from System.Collections.Generic import List
from System import String, DateTime

#define query condition
condition = QueryCondition()
condition.QueryValueVariables = List[String]()
condition.QueryValueVariables.Add('Decoder/projectValue')
condition.RowMax = 100
condition.StartTime = DateTime(2018, 8, 2)
condition.EndTime = DateTime(2018, 8, 3)

#start query database
result = dataAnalysis.GetSearchDataSet(condition)
print(result.Count) 

when I execute PythonEngine.Shutdown(), there is exception. do you know how to resolve it?

System.Runtime.Serialization.SerializationException
HResult=0x8013150C
Message=程序集“CyberStone.Atp.Modules.Analysis, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“CyberStone.Atp.Modules.Analysis.Models.SearchResModel”未标记为可序列化。
Source=mscorlib
StackTrace:
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray(WriteObjectInfo objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
at Python.Runtime.RuntimeData.Stash()
at Python.Runtime.Runtime.Shutdown()
at Python.Runtime.PythonEngine.Shutdown()
at CyberStone.Atp.Infrastructure.Python.PythonNetScriptRunner.Run(String scripttext, PythonNetScope userscope) in D:\repo\ATP56\CSharp\Base\CyberStone.Atp.Infrastructure\PythonNet\PythonNetScriptRunner.cs:line 211
at CyberStone.Atp.Modules.TestScript.PythonNet.ViewModels.PythonNetDocument.<>c__DisplayClass25_0.b__0() in D:\repo\ATP56\CSharp\Modules\CyberStone.Atp.Modules.TestScript\PythonNet\ViewModels\PythonNetDocument.cs:line 220
at System.Threading.Tasks.Task.Execute()

            PythonEngine.Initialize();
            try
            {
                using (PythonRuntime.Py.GIL())
                {
                    // Capture the output in a StringWriter
                    using (var outputWriter = new StringWriter())
                    {
                        // Redirect Python's sys.stdout to the custom StringWriter
                        var originalOutput = Console.Out;
                        Console.SetOut(outputWriter);

                        dynamic sys = Py.Import("sys");
                        dynamic pythonIO = Py.Import("io");

                        // Redirect Python's sys.stdout to a custom StringIO object
                        dynamic originalStdout = sys.stdout;
                        dynamic captureStream = pythonIO.StringIO();
                        sys.stdout = captureStream;

                        try
                        {
                            PyObject p = PythonEngine.Compile(_scripttext);

                            _scope.CreatePythonNetScope();
                            _scope.Scope.Exec(_scripttext);
                            //PythonRuntime.PythonEngine.Exec(_scripttext);
                        }
                        catch (Exception ex)
                        {
                            capturedOutput += $"{ex.Message};";
                        }
                        finally
                        {
                            // Reset sys.stdout to the original value
                            sys.stdout = originalStdout;
                        }

                        // Get the captured output from the StringIO object
                        capturedOutput += captureStream.getvalue().ToString();
                    }
                }
            }
            catch(Exception ex)
            {
            }
            finally
            {
                PythonEngine.Shutdown();
            }
    print('TODO')
  • If there was a crash, please include the traceback here.
    print('TODO')

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with PythonEngine.Shutdown() and RuntimeData.Stash() in the supplied stack trace, then reduce the script to a minimal example without the CyberStone assemblies. Reproduce it with Pythonnet 3.0.1 on the listed runtime; done means a confirmed reproduction and a documented resolution or regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.