Выполнить скрипт Python с аргументами разбора из C # - PullRequest
0 голосов
/ 13 октября 2019

, как вы можете видеть на картинках выше, я пытаюсь выполнить скрипт Python, который возвращает мне рекомендуемые фильмы, входные данные, которые ждет скрипт Python, следующие:

- movie_name "Iron Man" --top_n 10 1) принят путь от python

"- movie_name" "Iron Man" "--top_n" "10" 2) принят путь от python

Последние часы, в которые я ищуспособ дать им правильно, но я не могу. Вы можете видеть на картинке мою последнюю попытку. Изображение с Python , Изображение с vsCode

        string s = "\"Iron Man\"";
        string s1 = "\" --movie_name\"";
        string s2 = "\" --top_n \"";
        string s3 = "\"10\"";

        string arg = string.Format(@"\c C:\Users\Azizmaiden\Desktop\files\hello\KnnRecommender.py {0} {1} {2} {3}", s1, s, s2, s3);

        try
        {
            Process p1 = new Process();
            p1.StartInfo.FileName = arg;
            p1.StartInfo = new ProcessStartInfo(@"cmd.exe ", arg);
            p1.StartInfo.RedirectStandardOutput = true;
            p1.StartInfo.RedirectStandardInput = true;
            p1.StartInfo.UseShellExecute = false;
            p1.Start();
            p1.WaitForExit();
        }
        catch (Exception ex)
        {
            Console.WriteLine("There is a problem in your Python code: " + ex.Message);
        }
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();

Ответы [ 2 ]

0 голосов
/ 19 октября 2019

Нашли решение, и это следующее.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

string s1 = "--movie_name";
string s2 = "\"Iron Man\"";
string s3 = "--top_n";
string s4 = "10";

process.StartInfo = new ProcessStartInfo(@"cmd.exe ", @"/c C:\Users\Azizmaiden\Desktop\files\hello\KnnRecommender.py " + s1 + " " + s2 + " " + s3 + " " + s4)
{
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false,
    Verb = "runas"
};
process.Start();

string res = "";
StringBuilder q = new StringBuilder();
while (!process.HasExited)
{
    q.Append(process.StandardOutput.ReadToEnd()); 
}
string r = q.ToString();
res = r;
Console.Write("RESULTS: " + res.ToString());
0 голосов
/ 14 октября 2019

просто попробуйте эти первые строки вместо:

    string s = "Iron Man";
    string s1 = "--movie_name";
    string s2 = "--top_n";
    string s3 = "10";

    string arg = string.Format(@"/c ""C:\Users\Azizmaiden\Desktop\files\hello\KnnRecommender.py"" {0} ""{1}"" {2} {3}", s1, s, s2, s3);

Все имена аргументов, например --movie_name, должны быть без "
Название вашего фильма должно быть выделено", что проще для чтениявнутри вашего формата.
Если ваш файл KnnRecommender.py когда-нибудь окажется в пути, содержащем пробел, вы должны в любом случае заключить его в ".

...