2016-06-20 3 views
0

Я пытаюсь выполнить скрипт python из C#. Я нашел способ сделать это в другом посте по следующей ссылке: run a python script from c#. Тем не менее, я получаю сообщение об ошибке, когда процесс приходит к использованию линии (Process process = Process.Start(start)). Вот код, который я реализую:Ошибка при попытке запустить python.exe из C#

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 


namespace RunPy 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100 
      String cmd = "@C:/Program Files (x86)/Python27/python.exe"; 
      String argss = "C:/My_Python_lib/happyBirthday.py 'joe'"; 
      // Console.Write(argss); this line is just to test the output of the above argss 
      // Console.ReadLine(); this line goes with the above line to prevent the window from closing so fast 
      run_cmd(cmd, argss); 
      //ProcessStartInfo startInfo = new ProcessStartInfo(); 
      //startInfo.FileName = cmd; 
      //Process.Start(cmd); 

     } 
     private static void run_cmd(string cmd, string args) 
     { 
      ProcessStartInfo start = new ProcessStartInfo(); 
      start.FileName = cmd; 
      start.Arguments = args; 
      start.UseShellExecute = false; 
      start.RedirectStandardOutput = true; 
      using (Process process = Process.Start(start)) 
      { 
       using (StreamReader reader = process.StandardOutput) 
       { 
        string result = reader.ReadToEnd(); 
        Console.Write(result); 
       } 
      } 
     } 
    } 
} 

Здесь ошибка, что я получаю обратно:

Необработанное исключение типа «System.ComponentModel.Win32Exception» произошло в System.dll

Любая помощь будет принята с благодарностью. Благодаря!

+0

Почему вы используете slahes ('/') вместо обратных косых черт ('\') для путей? – zdimension

+0

Вы предлагаете использовать двойные кавычки (")? – DeeTee

+0

измените приведенную выше строку на это' String cmd = @ "C: \ Program Files (x86) \ Python27 \ python.exe"; ' –

ответ

2

Исправлена ​​неправильная инициализация переменной cmd. «@» Должно предшествовать кавычки (т. Е. @ «C:/...»). Конечно, использование косых черт вместо обратных косых символов в любом случае сводит на нет необходимость в дословной строке, поэтому вы можете вообще опустить «@».

String cmd = "C:/Program Files (x86)/Python27/python.exe"; 
+0

OMG это сработало! :) – DeeTee

Смежные вопросы