如何打开一个进程并使整个类都可以使用蒸汽读/写程序

本文关键字:可以使 程序 何打开 一个 进程 | 更新日期: 2023-09-27 18:05:28

我目前正在编写一个操作已经构建的现有控制台应用程序的应用程序。目前,我能够启动现有的应用程序,然后写入控制台并接收输出。但我需要我的应用程序基本上保持控制台应用程序在后台运行,保持应用程序打开,并准备向窗口编写新命令以接收更多信息。下面是我正在使用的当前代码。我想知道是否有一种方法可以在启动时调用此代码来启动控制台应用程序。

:

   private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        string ApplicationPath = "python";
        string ApplicationArguments = "Console/dummy.py";
        string returnValue;
        //Process PyObj = new Process();
        ProcessStartInfo PyObjStartInfo = new ProcessStartInfo();
        PyObjStartInfo.FileName = ApplicationPath;
        PyObjStartInfo.Arguments = ApplicationArguments;
        PyObjStartInfo.RedirectStandardInput = true;
        PyObjStartInfo.RedirectStandardOutput = true;
        PyObjStartInfo.UseShellExecute = false;
        //PyObjStartInfo.CreateNoWindow = true;
        //PyObj.StartInfo = PyObjStartInfo;
        Thread.Sleep(5000);
        using (Process process = Process.Start(PyObjStartInfo))
        {
            StreamWriter sw = process.StandardInput;
            StreamReader sr = process.StandardOutput;
            if (sw.BaseStream.CanWrite)
            {
                sw.WriteLine("auth");
            }
            sw.Close();
            sw.Close();
            returnValue = sr.ReadToEnd();
            MessageBox.Show(returnValue.ToString());
        }
        //Thread.Sleep(5000);
        //PyObj.WaitForExit();
        //PyObj.Close();
    }

正如您所看到的,这目前利用了一个按钮单击,但我希望代码在我的应用程序启动时立即运行。然后保持控制台应用程序运行并保存在内存中,这样我就可以与它进行交互。在c# .net中有什么办法做到这一点吗?

供参考。我可以调用的控制台应用程序是空白的,暂时只返回虚拟答案。下面是Python代码。

python代码:

  import os, pprint
def main():
    keepGoing = True
    while keepGoing:
      response = menu()
      if response == "0":
          keepGoing = False
      elif response == "auth":
          print StartAuthProcess()
      elif response == "verify":
          print VerifyKey(raw_input(""))
      elif response == "get":
          print Info()
      else:
          print "I don't know what you want to do..."
def menu():
    '''
    print "MENU"
    print "0) Quit"
    print "1) Start Autentication Process"
    print "2) Verify Key"
    print "3) Get Output"
    return raw_input("What would you like to do? ")
    '''
    return raw_input();
def StartAuthProcess():
    return 1;
def VerifyKey(key):
    if(key):
        return 1;
    else:
        return 0;
def Info():
    info = "{dummy:stuff}";
    return info;
main()

如何打开一个进程并使整个类都可以使用蒸汽读/写程序

有几个地方可以放置可以立即运行的代码。首先,你会看到一个program。cs,它有你的static void Main函数。这就是应用程序开始执行的地方。直到调用Application.Run()时才显示表单。这是放置早期初始化内容的好地方。

如果你想让事情发生当你的表单第一次打开,你可以覆盖虚拟Form.OnShown方法:

protected override void OnShown(EventArgs e) {
    base.OwnShown(e);
    // Call whatever functions you want here.
}

注意,你真的不应该在GUI线程(也就是你的按钮点击处理程序)中使用任何阻塞调用,比如Sleep。这将导致GUI挂起,感觉没有响应。我不确定你打算如何与后台进程交互(它是自动的,还是用户驱动的?)但是任何阻塞调用(即从标准输出读取)都应该发生在后台线程上。然后你可以使用Control.Invoke封送回UI线程的调用来更新控件,等等。