【问题标题】:Is there a way to conect the input/output of a console application to the output/input of another program有没有办法将控制台应用程序的输入/输出连接到另一个程序的输出/输入
【发布时间】:2019-12-01 19:01:50
【问题描述】:

我有一个我无法编辑的应用程序,它从控制台读取并写入它,我想知道如何读取程序所说的内容并将命令写回程序。

这适用于我的世界服务器,我想在其中阅读玩家所说的内容并根据所说的内容运行命令。 (服务器是我无法编辑的应用程序)

我无法为服务器创建修改,因为我正在使用一个模块来检查是否对文件进行了任何其他修改,如果是这种情况则无法加载。

【问题讨论】:

  • 不清楚你在问什么(至少对我来说)。你想编写一个与控制台交互的应用程序吗?在这种情况下你想使用什么语言?
  • 我想编写一个控制现有应用程序的应用程序。基本上,已经存在的应用程序有控制台 i/o,它说明正在发生的事情。我想接受应用程序所说的内容,如果满足特定条件,则向该应用程序的输入发送一个字符串,例如“保存当前状态”或“停止执行”,编程语言无关紧要,只要可以用于编写程序以通过控制台与另一个程序对话。基本上,我想要一个可以在控制台中模拟人类交互的程序。

标签: input console output


【解决方案1】:

我在 C# 中编写了一个简单的应用程序来开始使用,以重定向您在自己的应用程序中启动应用程序(在本例中为服务器)所需的 I/O 流。
首先我们创建一个System.Diagnostics.Process 类的新实例

var process = new Process();

然后我们指定开始信息

process.StartInfo = new ProcessStartInfo
{
    FileName = Console.ReadLine(), //Reads executable path from console
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false
};

然后我们添加一个事件处理程序,在这个例子中它只是写入带有“>”前缀的行

process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");

现在我们可以通过调用Process#Start()来启动这个过程

process.Start();

最后我们可以调用Process#BeginOutputReadLine() 没有这个OutputDataReceived 事件将永远不会触发

process.BeginOutputReadLine();

要发送命令,您可以使用进程'StandardInput

process.StandardInput.WriteLine("command");

带有示例输出的完整工作代码(使用 cmd.exe 测试,但必须与 MC 服务器一起使用)
代码:

static void Main(string[] args)
{
    Console.Write("Enter executable path: ");
    var process = new Process();
    process.StartInfo = new ProcessStartInfo
    {
        FileName = Console.ReadLine(), //Reads executable path, for example cmd is the input
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false
    };
    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");
    process.Start();
    process.BeginOutputReadLine();

    process.StandardInput.WriteLine("echo a");

    //Prevent closing
    Console.ReadKey();
}

输出:

Enter executable path: cmd
> Microsoft Windows [Version 10.0.18362.239]
> (c) 2019 Microsoft Corporation. Minden jog fenntartva.
>
> F:\VisualStudio\StackOverflow\StackOverflow\bin\Debug\netcoreapp2.1>echo a
> a
>

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    相关资源
    最近更新 更多