使用 C# 中的解析参数执行 Python 脚本

Execute Python Script With Parse Arguments From C#

如上图所示,我正在尝试执行 python 脚本,returns 我推荐了电影 python 脚本正在等待的输入如下:

--movie_name "Iron Man" --top_n 10 1) 从 python

接受的方式

"--movie_name" "Iron Man" "--top_n" "10" 2) 从 python

接受的方式

最后几个小时我正在寻找一种方法来正确地给他们,但我不能。你可以在图片中看到我最后一次尝试。Image from Python, Image from 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();

只需尝试以下第一行:

    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 文件在包含 space 的路径中结束,您必须用 " 将其包围。

找到解决方案,如下。

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());