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

时间:2019-10-13 16:52:31

标签: c# python ironpython

如您在上面的图片中看到的,我正在尝试执行一个python脚本,该脚本返回我推荐的电影,python脚本正在等待的输入如下:

-movie_name“钢铁侠” --top_n 10 1)从python接受的方式

“-电影名称”“钢铁侠”“ --top_n”“ 10” 2)从python接受的方式

最近几个小时,我正在寻找一种方法来适当地给他们,但我不能。您可以在图片中看到我的最后一次尝试。Image from PythonImage from vsCode

window.addEventListener('scroll', someFunc, false);

2 个答案:

答案 0 :(得分:0)

只需尝试以下第一行:

    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文件最终出现在包含空格的路径中,则无论如何都必须将其括起来。

答案 1 :(得分:0)

找到了解决方法,如下所示。

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