c# - 如何在 C# 中通过 shell 执行文件?

标签 c# .net

我一如既往地尝试使用 Process 类,但没有用。我所做的只是尝试运行一个 Python 文件,就像有人双击它一样。

这可能吗?

编辑:

示例代码:

string pythonScript = @"C:\callme.py";

string workDir = System.IO.Path.GetDirectoryName ( pythonScript );

Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";

我没有收到任何错误,但脚本没有运行。当我手动运行脚本时,我看到了结果。

最佳答案

这是我从 C# 执行 python 脚本的代码,带有重定向的标准输入和输出(我通过标准输入传递信息),是从网上某处的示例复制而来的。如您所见,Python 位置是硬编码的,可以重构。

    private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
    {

        ProcessStartInfo startInfo;
        Process process;

        string ret = "";
        try
        {

            startInfo = new ProcessStartInfo(@"c:\python25\python.exe");
            startInfo.WorkingDirectory = workingDirectory;
            if (pyArgs.Length != 0)
                startInfo.Arguments = script + " " + pyArgs;
            else
                startInfo.Arguments = script;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardInput = true;

            process = new Process();
            process.StartInfo = startInfo;


            process.Start();

            // write to standard input
            foreach (string si in standardInput)
            {
                process.StandardInput.WriteLine(si);
            }

            string s;
            while ((s = process.StandardError.ReadLine()) != null)
            {
                ret += s;
                throw new System.Exception(ret);
            }

            while ((s = process.StandardOutput.ReadLine()) != null)
            {
                ret += s;
            }

            return ret;

        }
        catch (System.Exception ex)
        {
            string problem = ex.Message;
            return problem;
        }

    }

关于c# - 如何在 C# 中通过 shell 执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/749680/

相关文章:

c# - 为什么这会产生可为空数组/如何创建不可为空数组

c# - 无法更改 sql server 文件数据库大小

c# - 从 MethodInfo 打印方法的完整签名

c# - WPF 执行两个交替的 UI 任务

c# - Task.Delay 是否真正像 I/O 操作那样异步,即它是否依赖于硬件和中断而不是线程?

c# - 检测 WPF 控件何时相对于其父控件移动

c# - 如何列出省略属性访问器的接口(interface)方法

c# - 如何将字符串转换为int C#

java - 相当于 C# 中的 ASM 类 (Java)

c# - 如何在运行时在 ASP.NET MVC 中创建强类型 View ?