如何在 Windows 上使用 C# 打开 Ubuntu 的 bash.exe shell?

How to open Ubuntu's bash.exe shell using C# on Windows?

如标题所述,我想在我的 windows 电脑上打开 ubuntu-shell,传递一个 "cd /mnt/c/users/xyz/desktop" 然后传递一个 "python3 some_script.py arg1, arg2" 给它

如果通过鼠标点击手动完成,但从代码中完成,所有这些都非常有效(见下文:) 它不会向打开的控制台写入任何内容。

        string ExecuteCommand(string command)
        {
            // Execute wsl command:                
            var StartInfo = new ProcessStartInfo
            {                    
                FileName = @"bash.exe",
                WorkingDirectory = @"C:\Windows\System32",
                //Arguments = "/c " + "root@DESKTOP-OUTEVME:~#",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = false,           
                WindowStyle = ProcessWindowStyle.Normal,
            };
            using (var process = Process.Start(StartInfo)) 
            {
                process.StandardInput.WriteLine();
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, e) => MessageBox.Show(e.Data);
                process.BeginOutputReadLine();
                process.StandardInput.WriteLine(command);                 
                process.StandardInput.WriteLine("exit");
                process.WaitForExit();
                //result = process.StandardOutput.ReadToEndAsync().Result;
            }
            return result;                
        }
        return ExecuteCommand(@"wsl cd /mnt/c/users/shho3/desktop"); 

有人知道我哪里做错了吗?

非常感谢!

您可以在命令行中传递所有内容,而不是通过管道传递到进程中。我想这会给你省去很多麻烦。试试 bash.exe -c "cd /mnt/c/Users/shho3/Desktop; python some_script.py arg1 arg2":

Process.Start("bash.exe", "-c \"cd /mnt/c/Users/shho3/Desktop; python some_script.py arg1 arg2\"").WaitForExit()

或者,您也可以将工作目录设置为 C:\Users\shho3\Desktop(而不是 C:\Windows\System32)并调用 bash.exe -c "python some_script.py arg1 arg2",这样您甚至不必转换路径:

Process.Start(new ProcessStartInfo("bash.exe", "-c \"python some_script.py arg1 arg2\"") {
  WorkingDirectory = "C:\Users\ssho3\Desktop"
}).WaitForExit()