2009-04-14 10 views
5

Ho provato a utilizzare la classe Process come sempre ma non ha funzionato. Tutto quello che sto facendo è provare a eseguire un file Python come se qualcuno l'avesse fatto doppio clic.Come eseguire shell in un file in C#?

È possibile?

EDIT:

codice di esempio:

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

non ho ricevuto alcun errore, ma lo script non viene eseguito. Quando eseguo lo script manualmente, vedo il risultato.

+0

Puoi condividere il tuo codice? –

+0

Cosa intendi con "non ha funzionato"? –

+0

Era la classe System.Diagnostics.Process? per esempio. http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

risposta

7

Ecco il mio codice per l'esecuzione di uno script python da C#, con uno standard input e output reindirizzato (ho passato informazioni tramite l'input standard), copiato da un esempio sul web da qualche parte. La posizione di Python è hardcoded come puoi vedere, può refactoring.

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

Grazie, sai come ottenere la posizione di Python a livello di programmazione? –

5

Process.Start dovrebbe funzionare. se così non fosse, pubblicherebbe il tuo codice e l'errore che stai ricevendo?

3

Hai dimenticato proc.Start() alla fine. Il codice che hai dovrebbe funzionare se chiami Start().

Problemi correlati