2009-04-14 2 views
5

언제나처럼 Process 클래스를 사용해 보았지만 작동하지 않았습니다. 내가하고있는 일은 누군가가 더블 클릭 한 것처럼 파이썬 파일을 실행하려고하는 것이다.C#에서 파일을 셸 실행하는 방법?

가능합니까?

편집 :

샘플 코드 :

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

내가 어떤 오류가 발생하지 않지만, 스크립트가 실행되지 않습니다. 스크립트를 수동으로 실행하면 결과가 표시됩니다.

+0

코드를 공유해주십시오. –

+0

"작동하지 않았다"는 의미는 무엇입니까? –

+0

System.Diagnostics.Process 클래스였습니까? 예 : http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx –

답변

7

다음은 C#에서 파이썬 스크립트를 실행하기위한 코드입니다. 리다이렉트 된 표준 입력과 출력 (표준 입력을 통해 정보를 전달합니다)이 웹상의 예제에서 복사됩니다. 파이썬 위치는 당신이 볼 수있는 것처럼 하드 코딩되어 있으며, 리팩토링 할 수 있습니다.

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

감사합니다. 파이썬 위치를 프로그래밍 방식으로 얻는 방법을 알고 있습니까? –

5

Process.Start. 그렇지 않으면 코드와 오류를 게시 하시겠습니까?

3

끝에 proc.Start()를 잊어 버렸습니다. Start()를 호출하면 코드가 작동해야합니다.

관련 문제