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 结束