C# 在Linux系统下 通过 Bash 调用Python库进行交互

发布时间 2023-09-18 21:28:49作者: 初久的私房菜

Bash代码

    public class BashScriptRunner
    {
        public static async Task<string> ExecuteBash(string workDirectory, string command, string outputIndicator)
        {
            var processInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{command}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                WorkingDirectory = workDirectory
            };

            using var process = new Process { StartInfo = processInfo };
            process.Start();

            try
            {
                await process.WaitForExitAsync(new CancellationTokenSource(30000).Token);
            }
            catch (TaskCanceledException e)
            {
                var error = string.Empty;
                try
                {
                    error = await process.StandardError.ReadToEndAsync();
                }
                catch (Exception)
                {
                    // ignored
                }

                return default;
            }

            if (process.ExitCode < 0)
            {
                string errors = await process.StandardError.ReadToEndAsync();
                throw new Exception(errors);
            }
            else
            {
                var processOutput = process.StandardOutput;

                if (string.IsNullOrEmpty(outputIndicator)) return await processOutput.ReadToEndAsync();

                while (await processOutput.ReadLineAsync() is { } block)
                {
                    if (block == outputIndicator)
                    {
                        return await processOutput.ReadToEndAsync();
                    }
                }
                return await processOutput.ReadToEndAsync();

            }
        }

    }

调用代码

BashScriptRunner.ExecuteBash(调用bash的路径, 需要执行的代码, "");