首页 > 解决方案 > 如何使用 C# 执行带有传递参数的 python 文件

问题描述

我正在尝试通过创建一个新进程并传递 ProcessStartInfo 来使用 C# 执行 detect.py 文件

这是我的方法

         Process p = new Process();
            ProcessStartInfo info = new ProcessStartInfo
            {
                FileName = @"C:\Users\malsa\anaconda3\python.exe",
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = false,
                UseShellExecute = false
            };
            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine(string.Format("cd {0}", @"C:\Users\malsa\Desktop\Yolo"));
                    sw.WriteLine(string.Format("detect.py --source {0}", ImagePath));
                }
            }

            p.WaitForExit();

现在参数应该传递给 cmd,但是由于我将文件设置为 python.exe,所以参数应该用 python 编写。

使用 cmd 运行 detect.py

如图所示,我们如何通过在 cmd 中提供 --source ImgFile.jpg 来执行 detect.py。问题是如何通过提供诸如 ImgFile.jpg 之类的参数在 Python-Shell 中执行 detect.py 以便我可以在 C# 中编写这些参数?

我尝试过诸如

subprocess.call(['C:\Users\malsa\Desktop\Yolo\detect.py', 0])

但我无法让它工作。

标签: pythonc#

解决方案


为什么不使用参数?:

 Process p = new Process();
            ProcessStartInfo info = new ProcessStartInfo
            {
                FileName = @"C:\Users\malsa\anaconda3\python.exe",
                RedirectStandardError = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                // here 3 args with name of program python with 2 args
                Arguments = string.Format("{0} --source {1} {2}", "detect.py", "0", "image.jpg")
            };
            p.StartInfo = info;
            p.Start();

推荐阅读