简体   繁体   English

为什么C#不等待python代码完成?

[英]Why doesn't c# wait for python code to finish?

I can run my code from cmd however the c# code doesn't wait for python to finish it's just closing the window. 我可以从cmd运行我的代码,但是C#代码不等待python完成它,而只是关闭窗口。

I have tried ironpython, but that gives me error for unknown libraries that I'm importing in python. 我已经尝试了ironpython,但是这给我在python中导入的未知库的错误。

          string result = string.Empty;
            try
            {


                var info = new ProcessStartInfo();
             info.FileName = @"D:\Program Files (x86)\Python\Python36\python.exe";
                info.Arguments = @"D:\detect.py" + " " + "--images img";

                info.RedirectStandardInput = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                info.CreateNoWindow = false;
            using (var proc = new Process())
            {
                proc.StartInfo = info;
                proc.Start();
                   proc.WaitForExit();
                   if (proc.ExitCode == 0)
                       {
                           result = proc.StandardOutput.ReadToEnd();
                       }
             }

                richTextBox1.Text += result;

            }
            catch (Exception ex)
            {
                throw new Exception("Script failed: " + result, ex);
            }

Python code: Python代码:

from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2


print("a")

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True, help="path to images         directory")
args = vars(ap.parse_args())

# initialize the HOG descriptor/person detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# loop over the image paths
imagePaths = list(paths.list_images(args["images"]))
print("b")
for imagePath in imagePaths:
    # load the image and resize it to (1) reduce detection time
    # and (2) improve detection accuracy
    image = cv2.imread(imagePath)
    image = imutils.resize(image, width=min(400, image.shape[1]))
    orig = image.copy()

    print('c')
        ...There are more code here but it the window is already closed by that time

"a" and "b" appears in the result, however "c" never does, I need to give arguments from c# to python and get some result values back, any ideas? 结果中出现“ a”和“ b”,但是“ c”从未出现,我需要将c#的参数提供给python,并返回一些结果值,有什么想法吗?

The problem seems to be with accessing the image folder from python side, I managed to solve by placing both the python file and the image folder inside bin/Debug/ Then the above c# code will work, however not in everycase one python file started and never finished, the following c# code solved that problem: 问题似乎与从python端访问图像文件夹有关,我设法通过将python文件和图像文件夹都放在bin / Debug /中来解决,然后上述c#代码将起作用,但是在每种情况下都无法启动一个python文件,并且从未完成,以下c#代码解决了该问题:

     System.Diagnostics.Process process = new System.Diagnostics.Process();
          process.StartInfo = new System.Diagnostics.ProcessStartInfo()
          {
              UseShellExecute = false,
              CreateNoWindow = false,
              WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
              FileName = "cmd.exe",
              Arguments = @"/C python detect_slow.py --images img", 
              RedirectStandardError = true,
              RedirectStandardOutput = true
          };
          process.Start();
          string output = process.StandardOutput.ReadToEnd();
          process.WaitForExit();

          richTextBox1.Text += output;

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

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