【问题标题】:Pass huge amount of string from Python to C#将大量字符串从 Python 传递到 C#
【发布时间】:2020-12-24 13:50:41
【问题描述】:

所以我在 python 中有这段代码,可以将图像转换为 base64。我在 C# winforms 中有这段代码,它收集 base64 并在图像中再次转换。

Python 代码:

import base64

imgtob64 = open('Resources/yudodis.jpg', 'rb')
imgtob64_read = imgtob64.read()
imgb64encode = base64.encodebytes(imgtob64_read)

print(imgb64encode)

C#代码:

string TestPath3 = @"C:\Users\chesk\Desktop\imagetobase64.py";
string b64stringPython;
string error;

            var startProcess = new ProcessStartInfo
            {
                FileName = pythonInterpreter, Arguments = string.Format($"\"{TestPath3}\""),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
            };
         

            using (Process process = Process.Start(startProcess))
            {
                try
                {
                    error = process.StandardError.ReadToEnd();
                    b64stringPython = process.StandardOutput.ReadToEnd();

                    lblTestOutput.Text = b64stringPython;
                    lblError.Text = error;
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }

如果我使用的是包含少于 4,000 个 base64 的小图像,则两边的代码都可以正常工作。当我发送包含超过 5,000 个 base64 的 base64 数据时,C# 中的系统突然停止工作(或根据我的理解突然停止接受来自 python 的数据)。

您认为这可能是什么问题?为什么 C# 在接受来自 python 的大量标准输出时会出现问题?

【问题讨论】:

  • 结局是什么?您正在使用 ReadTpEnd() 它将读取到流的末尾并且不会等到 python 脚本完成。您需要做的是用一个不在传输中的字符来终止每次传输,或者在每次传输的开头放置一个字节数,到 c# 将知道每次传输在哪里完成。
  • 感谢您的解释!根据我对您的解释的理解,python 过程没有完成,因为 C# 不等待它完成。对吗?
  • 是的。 c# ReadToEnd() 在python将所有数据写入标准输出之前。
  • 我现在明白了。非常感谢!

标签: python c# base64


【解决方案1】:

我调试了现有代码,发现冲突发生在标准错误部分。所以我删除它并替换我的`

ReadToEnd()

ReadLine()

它工作得非常好。这是我更新的代码。

 using (Process process = Process.Start(startProcess))
            {
                try
                {
                    process.StandardInput.WriteLine(b64stringCSharp);
                    process.StandardInput.Close();

                    
                    //error = process.StandardError.ReadToEnd();
                    b64stringPython = process.StandardOutput.ReadLine();
                    
                    //lblTestOutput.Text = b64stringPython;
                    //lblError.Text = error;
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }

【讨论】:

  • 只要 python 脚本在写入结束时添加返回,修复就会起作用。这是在 base 64 编码字符串的末尾添加返回值的一种组合。
猜你喜欢
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 2015-10-10
  • 2014-02-24
  • 2021-08-13
  • 2015-12-23
相关资源
最近更新 更多