1 需求 C# 启动使用pyinstaller打包好的.exe 的python程序,隐藏python运行的cmd窗口,并将python程序的输出信息显示在C#的控件上
Process p = new Process();
p.StartInfo.FileName = "./app.exe"; #python打包的.exe 程序
p.StartInfo.UseShellExecute = false;
p.EnableRaisingEvents = true;
p.StartInfo.RedirectStandardInput = true; //重定向标准输入输出
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true; //
p.StartInfo.CreateNoWindow = true; #隐藏窗体
#订阅下面的事件
p.OutputDataReceived += new DataReceivedEventHandler(scu_pcomProcess_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(Onscu_pcomerrorDataReceived);
p.Exited += new EventHandler(Onscu_pcomProcessExit);
p.Start();
#下面这两句是必须的,增加他们才能在上面订阅的事件中获得标准输入输出的消息
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
2 在python程序中使用了print("信息") 和sys.stdout.write("")的地方要增加sys.stdout.flush(),刷新缓存,这样C#程序才能实时获得打印的消息
import sys
print("1234")
sys.stdout.flush() //刷新缓存
3 python 调用C#程序
(1) python端
from subprocess import Popen,PIPE
import time
p=Popen('pipetest.exe',shell=True,stdin=PIPE,stdout=PIPE)
s=b"123\r\n" //一定要有回车符
p.stdin.write(s)
p.stdin.flush() //一定要刷新缓存
print(p.stdout.readline())
time.sleep(3)
p.stdin.write(s)
p.stdin.flush()
print(p.stdout.readline())
(2) C#端
int i = 0;
while(true)
{
i += 1;
string read = Console.ReadLine();
Console.WriteLine(i.ToString()+read);
Thread.Sleep(3000);
}
3 结束
C# 调用 Python .exe 并交互

本文介绍如何使用 C# 启动并隐藏由 PyInstaller 打包的 Python 程序,同时捕获其输出信息进行交互。通过创建进程并设置相关属性,可以实现在 C# 中读取 Python 程序的标准输出和错误输出。此外,还展示了 Python 如何调用 C# 程序并进行双向通信。
823

被折叠的 条评论
为什么被折叠?



