我正在开发一个窗口表单应用程序(C#),它应该启动外部进程并在表单应用程序中显示来自exe的一些结果和/或错误消息。
我似乎无法在表单应用程序和python中创建的外部进程(exe)之间形成命名管道连接。 exe启动并正常工作,但它似乎没有保持命名管道连接。所以,我无法从exe中获得任何消息。
exe是用pyinstaller和命名管道连接似乎与窗口控制台应用程序配对时工作得很好,即我可以从exe回到控制台应用程序的消息。
Consolse App
下面的脚本可以从exe到控制台返回消息。
namespace pipeConsoleApp
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream("teropipe");
Console.Write("Attempting to connect to the pipe...");
System.Diagnostics.Process.Start(@"my\path\to\external\app\tempp.exe");
pipeClient.Connect();
Console.WriteLine("Connected to the pipe");
Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances);
StreamWriter writer = new StreamWriter(pipeClient);
StreamReader reader = new StreamReader(pipeClient);
string temp;
while ((temp = reader.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", temp);
}
Console.Write("Press Enter to continue..");
Console.ReadLine();
}
}
但是当我在窗体应用程序上尝试类似的东西时,我无法从python服务器获取任何内容
表单应用
虽然我对表单应用程序使用了类似的方法,但不会返回任何消息。实际上,看起来命名的管道连接不能保持打开以便表单进行通信。
namespace pipeDemoForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void okayButton_Click(object sender, EventArgs e)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream("teropipe");
//MessageBox.Show("attempting to connect");
System.Diagnostics.Process.Start(@"my\path\to\external\app\tempp.exe");
pipeClient.Connect();
string numb = pipeClient.NumberOfServerInstances.ToString();
MessageBox.Show("There are currently {0} pipe server instances open", numb);
if (pipeClient.IsConnected)
{
MessageBox.Show("There are currently {0} pipe server instances open", pipeClient.NumberOfServerInstances.ToString());
}
}
}
}
Python脚本 - tempp.exe
以下是python脚本,我已经使用pyinstaller打包到onefile exe中。
import win32pipe
import win32file
def process():
pipe_handle = win32pipe.CreateNamedPipe(r'\\.\pipe\teropipe',
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
1,65536,65536,300,None)
win32pipe.ConnectNamedPipe(pipe_handle, None)
# business logic
..................
#write some output to the form app
win32file.WriteFile(pipe_handle,"some string return from above")