2009-04-14 10 views
5

J'ai essayé d'utiliser la classe Process comme toujours mais cela n'a pas fonctionné. Tout ce que je fais est d'essayer d'exécuter un fichier Python comme si quelqu'un l'avait double-cliqué.Comment shell exécuter un fichier en C#?

Est-ce possible?

EDIT:

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

je ne suis pas d'erreur, mais le script est pas exécuté. Quand je lance le script manuellement, je vois le résultat.

+0

Pouvez-vous s'il vous plaît partager votre code? –

+0

Que voulez-vous dire par "ne travaillait pas"? –

+0

Était-ce la classe System.Diagnostics.Process? par exemple. http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

Répondre

7

Voici mon code pour l'exécution d'un script python à partir de C#, avec une entrée et une sortie standard redirigées (je passe des informations via l'entrée standard), copiées à partir d'un exemple sur le web quelque part. L'emplacement de Python est codé en dur comme vous pouvez le voir, peut refactoriser.

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

Merci, savez-vous comment obtenir l'emplacement python par programme? –

5

Process.Start devrait fonctionner. Si ce n'est pas le cas, afficheriez-vous votre code et l'erreur que vous obtenez?

3

Vous avez oublié proc.Start() à la fin. Le code que vous avez devrait fonctionner si vous appelez Start().

Questions connexes