【问题标题】:How to execute python file with passing arguments using C#如何使用 C# 执行带有传递参数的 python 文件
【发布时间】:2020-09-19 22:47:43
【问题描述】:

我正在尝试通过创建一个新进程并传递 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 编写。

Running detect.py using cmd

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

我已经尝试过诸如

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

但我无法让它工作。

【问题讨论】:

  • this 能解决您的问题吗?
  • 我已经看到了,但是你可以看到传递的参数只是(整数),这很容易做到,但是我怎样才能将图像文件传递给 detect.py
  • @MohammedAlsabi 将图像文件作为泡菜文件发送?
  • 不可能,因为detect.py需要一个图像文件

标签: python c#


【解决方案1】:

为什么不使用参数?:

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

【讨论】:

  • 这正是我所需要的,它工作成功,我正在使用 StandardInput Stream 编写参数,但是当我将参数传递给 Argument 属性时它工作了。
  • 标准输入用于在os python下创建命令
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
相关资源
最近更新 更多