Friday, April 29, 2011

How to shell execute a file in C#?

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?

EDIT:

Sample code:

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.

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

  • 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;
            }
    
        }
    
    Joan Venge : Thanks, do you know how to get the python location programmatically?
  • You forgot proc.Start() at the end. The code you have should work if you call Start().

0 comments:

Post a Comment