简体   繁体   English

如何使用 C# 传递参数来执行 python 文件

[英]How to execute python file with passing arguments using C#

I'm trying to execute the detect.py file using C# by creating a new process and passing ProcessStartInfo我正在尝试通过创建一个新进程并传递 ProcessStartInfo 来使用 C# 执行 detect.py 文件

Here is my method这是我的方法

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

For now the arguments should be passed to cmd, but since am setting the file to python.exe the arguments should be written in python.现在参数应该传递给 cmd,但是由于我将文件设置为 python.exe,参数应该用 python 编写。

Running detect.py using cmd使用cmd运行detect.py

As shown in the image this how we can execute the detect.py by giving the --source ImgFile.jpg in cmd.如图所示,我们如何通过在 cmd 中提供 --source ImgFile.jpg 来执行detect.py。 The problem is that how can I execute the detect.py in Python-Shell by giving arguments such as ImgFile.jpg so that I can write these arguments in C# ?问题是如何通过提供 ImgFile.jpg 等参数在 Python-Shell 中执行 detect.py 以便我可以在 C# 中编写这些参数?

I have tried something such as我尝试过诸如

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

but I couldn't get it work.但我无法让它工作。

why dont use arguments?:为什么不使用参数?:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM