如何Shell执行在C#中的文件? [英] How to shell execute a file in C#?

查看:141
本文介绍了如何Shell执行在C#中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Process类一如既往,但没有奏效。所有我做的是试图运行像有人双点击它Python文件。

I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.

这可能吗?

编辑:

示例代码:

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";



我没有得到任何错误,但脚本无法运行。当我手动运行该脚本,我看到的结果。

I don't get any error, but the script isn't run. When I run the script manually, I see the result.

推荐答案

下面是我的代码从C#执行python脚本,用重定向标准输入和输出(I传递通过标准的输入信息),从一个例子地方复制在网络上。 Python的位置是硬编码的,你可以看到,可以重构。

Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.

    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;
        }

    }

这篇关于如何Shell执行在C#中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆