我可以从cmd运行我的代码,但是C#代码不等待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代码:
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”和“ b”,但是“ c”从不出现,我需要将c#的参数提供给python,并返回一些结果值,有什么想法吗?
答案 0 :(得分:0)
问题似乎出在从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;