簡體   English   中英

如何使用 C# 傳遞參數來執行 python 文件

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

我正在嘗試通過創建一個新進程並傳遞 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])

但我無法讓它工作。

為什么不使用參數?:

 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