2009-04-14 25 views
5

Intenté utilizar la clase Process como siempre, pero eso no funcionó. Todo lo que hago es intentar ejecutar un archivo de Python como si alguien lo hubiera hecho doble clic.¿Cómo ejecutar un archivo en C#?

¿Es posible?

EDIT:

Código de ejemplo:

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

que no reciben ningún error, pero el guión no se ejecuta. Cuando ejecuto el script manualmente, veo el resultado.

+0

¿Puede compartir su código? –

+0

¿Qué quiere decir con "no funcionó"? –

+0

¿Era esa la clase System.Diagnostics.Process? p.ej. http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

Respuesta

7

Aquí está mi código para ejecutar una secuencia de comandos python desde C#, con una entrada y salida estándar redirigida (paso la información a través de la entrada estándar), copiada de un ejemplo en la web en alguna parte. La ubicación de Python está codificada como puede ver, puede refactorizarse.

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

Gracias, ¿sabes cómo obtener la ubicación de python programáticamente? –

5

Process.Start debería funcionar. si no lo hace, ¿publicaría su código y el error que está recibiendo?

3

Has olvidado proc.Start() al final. El código que tienes debería funcionar si llamas a Start().

Cuestiones relacionadas