2009-04-14 18 views
5

İşlem sınıfını her zaman olduğu gibi kullanmayı denedim, ancak çalışmadı. Tek yaptığım, birisinin çift tıkladığı gibi bir Python dosyasını çalıştırmaya çalışmak.C# dosyasında dosya yürütme nasıl kabuklanır?

Mümkün mü?

DÜZENLEME:

örnek kod:

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

herhangi bir hata alamadım, ama senaryo çalıştırılmaz. Komut dosyasını manuel olarak çalıştırdığımda sonucu görüyorum.

+0

Lütfen kodunuzu paylaşabilir misiniz? –

+0

"Çalışmıyor" ile ne demek istiyorsun? –

+0

System.Diagnostics.Process sınıfı bu muydu? Örneğin. http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

cevap

7

C# 'den bir python betiğini yürütmek için kodum, yeniden yönlendirilmiş bir standart giriş ve çıkış (standart girdiden bilgi aktarıyorum) ile web'deki bir örnekte kopyalanmış bir yerde. Gördüğünüz gibi Python konumu sabit kodlanmış, refactor olabilir.

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

Teşekkürler, python yerini program aracılığıyla nasıl edineceğinizi biliyor musunuz? –

5

Process.Start çalışmalıdır. yoksa, kodunuzu ve aldığınız hatayı postalar mısınız?

3

Sonunda proc.Start() öğesini unutmuşsunuzdur. Başlat() öğesini çağırırsanız sahip olmanız gereken kod.

İlgili konular