当前位置: 首页 > 编程语言 > C#

如何在C#应用程序中调用Perl脚本?分享

时间:2023-04-10 21:54:16 C#

如何在C#应用程序中调用Perl脚本?我想捕获Perl程序的输出并在C#Windows窗体的文本框中显示输出数据(屏幕上的字符串)。这是我的主要C#代码:publicpartialclassfrmMain:Form{privateProcessmyProcess=null;publicfrmMain(){InitializeComponent();}publicdelegatevoidUpdateUIDelegate(stringdata);privatevoidbtnRun_Click(objectsender,EventArgse){myProcess=newProcess();ProcessStartInfomyProcessStartInfo=newProcessStartInfo("perl.exe");myProcessStartInfo.Arguments="test.pl";myProcessStartInfo.UseShellExecute=false;myProcessStartInfo.RedirectStandardOutput=true;myProcessStartInfo.WindowStyle=ProcessWindowStyle.Hidden;myProcessStartInfo.CreateNoWindow=true;myProcess.StartInfo=myProcessStartInfo;myProcess.OutputDataReceived+=newDataReceivedEventHandler(myProcess_OutputDataReceived);myProcess.Start();myProcess.BeginOutputReadLine();}voidmyProcess_OutputDataReceived(objectsender,DataReceivedEventArgse){if(txtOutput.InvokeRequired){UpdateUIDelegateupdateDelegate=newUpdateUIDelegate(UpdateUI);这个。调用(updateDeleg吃了,e.Data);}}voidUpdateUI(stringdata){txtOutput.Text+=data+"rn";}}和test.pl的代码:my@a=qw{12345678910111213141516171819};我的@b=qw{abcdefghijklmnopqrs};打印“开始”。"n";while(my($item1,$item2)=(splice(@a,0,1),splice(@b,0,1))){print'Item1:'.$item1。"n";打印“项目2:”。$item2。"n";警告“完成一项”。"n";睡觉(1);我有一个问题,输出数据只显示在文本框上,直到我找到它时Perl完成,更有趣的是,如果我对控制台应用程序(C#)做同样的事情,一切似乎都很好。下面是控制台应用程序的代码:classProgram{staticvoidMain(string[]args){ProcessmyProcess=newProcess();ProcessStartInfomyProcessStartInfo=newProcessStartInfo("perl.exe");myProcessStartInfo.Arguments="test.pl";myProcessStartInfo.UseShellExecute=false;myProcessStartInfo.RedirectStandardOutput=true;myProcess.StartInfo=myProcessStartInfo;myProcess.OutputDataReceived+=newDataReceivedEventHandler(myProcess_OutputDataReceived);myProcess.Start();myProcess.BeginOutputReadLine();控制台.Read();}staticvoidmyProcess_OutputDataReceived(objectsender,DataReceivedEventArgse){Console.WriteLine(e.Data);我试图弄清楚我的表单应用程序发生了什么,但仍然没有找到任何线索。还有一件事是我无法通过Windows窗体应用程序获得警告消息。您将需要使用多个线程,这样它就不会中断您的UI。我有一个相当大的实用程序类,它在自己的线程和管道上启动进程以委托事件。抱歉举个例子,但我实际上是在匆匆忙忙。但是,使用Perl脚本需要注意的另一件事是它们不能很好地自动刷新输出。您需要输入:local$|=1;在您正在运行的脚本的顶部,因此它会自动刷新。首先,您必须更新事件处理程序}UIe更新.Data);}并在btnRun_Click中加入这一行以上是C#学习教程:HowtocallPerlscriptinC#application?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——proc.WaitForExit();本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: