2009-04-14 64 views
5

Tôi đã thử sử dụng lớp Process như mọi khi nhưng điều đó không hiệu quả. Tất cả những gì tôi đang làm là cố gắng chạy một tệp Python như một người nào đó đã nhấp đúp vào nó.Làm cách nào để thực thi tệp trong C#?

Có thể không?

EDIT:

Mẫu mã:

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

tôi không nhận được bất kỳ lỗi, nhưng kịch bản không chạy. Khi tôi chạy kịch bản theo cách thủ công, tôi thấy kết quả.

+0

Bạn có thể chia sẻ mã của mình không? –

+0

Bạn có ý nghĩa gì bởi "không hoạt động"? –

+0

Đó có phải là lớp System.Diagnostics.Process không? ví dụ. http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

Trả lời

7

Đây là mã của tôi để thực thi tập lệnh python từ C#, với đầu vào và đầu ra tiêu chuẩn được chuyển hướng (tôi chuyển thông tin qua đầu vào tiêu chuẩn), được sao chép từ ví dụ trên web ở đâu đó. Vị trí Python được mã hóa cứng như bạn có thể thấy, có thể cấu trúc lại.

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

Cảm ơn, bạn có biết làm thế nào để có được vị trí python theo lập trình? –

5

Process.Start sẽ hoạt động. nếu không, bạn sẽ đăng mã của bạn và lỗi bạn đang nhận được?

3

Bạn quên proc.Start() ở cuối. Mã bạn phải làm việc nếu bạn gọi hàm Start().

Các vấn đề liên quan