How to shell execute a file in C#?

后端 未结 3 783
难免孤独
难免孤独 2020-12-29 17:30

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.

Is it possible?

<
相关标签:
3条回答
  • 2020-12-29 18:05

    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;
            }
    
        }
    
    0 讨论(0)
  • 2020-12-29 18:13

    You forgot proc.Start() at the end. The code you have should work if you call Start().

    0 讨论(0)
  • 2020-12-29 18:24

    Process.Start should work. if it doesn't, would you post your code and the error you are getting?

    0 讨论(0)
提交回复
热议问题