Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SerializationException when PythonEngine.Shutdown() #2221

Open
muler415 opened this issue Aug 14, 2023 · 2 comments
Open

SerializationException when PythonEngine.Shutdown() #2221

muler415 opened this issue Aug 14, 2023 · 2 comments

Comments

@muler415
Copy link

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')
@wrexbe
Copy link

wrexbe commented Aug 25, 2023

When my application is exiting to work around the bug I do this.

typeof(Runtime)
.GetField("ProcessIsTerminating", BindingFlags.Static | BindingFlags.NonPublic )!
.SetValue(null, true);
PythonEngine.Shutdown();

I do not recommend this as a workaround if you plan on starting it up again.

@muler415
Copy link
Author

muler415 commented Sep 1, 2023

I used other options to resolve this issue by recreating new class for serialization purpose. this works well in my application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants