首页 > 解决方案 > 在 c# 上运行带有参数的 python 脚本并且在 cmd 上不会崩溃

问题描述

不知何故,我正在运行一个带有参数的 python 脚本,在 cmd 上运行良好,但是当我通过我的 C# 传递它时,它似乎没有正确传递参数。

命令结果:

C:\Users\Sick\source\repos\phoneScraper\phoneScraper\bin\Debug\netcoreapp3.1\Captchas>script.py dztfi.png 
mysycd

代码:

static string run_cmd(string arg) // arg value = image.png
    {
        string result = ""; 
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:\Users\Sick\AppData\Local\Programs\Python\Python38-32\python.exe";//cmd is full path to python.exe
        start.Arguments = "Captchas/script.py " + arg;//args is path to .py file and any cmd line args
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                result = reader.ReadToEnd();
                Console.WriteLine(result);
            }
        }
        return result;
    }

    c# error:
Traceback (most recent call last):
  File "Captchas/script.py", line 11, in <module>
    close = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\core\src\matrix.cpp:757: error: (-215:Assertion failed) dims <= 2 && step[0] > 0 in function 'cv::Mat::locateROI'

Python代码:

import cv2
import numpy as np
import pytesseract
import sys

img = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)

img = cv2.bitwise_not(img)

kernel = np.ones((7, 7), np.uint8)
close = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
newkernel = np.ones((5, 5), np.uint8)
inv = cv2.erode(close, newkernel, iterations=1)

inv = cv2.bitwise_not(inv)

custom_config = r'-l eng --oem 3 --psm 7 -c tessedit_char_whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"'
text = pytesseract.image_to_string(inv, config=custom_config)
print(text)

谢谢!

标签: pythonc#cmdcv2

解决方案


您应该指定 ProcessStartInfo 的 WorkingDirectory。例如,您在应用程序中使用 Application.StartupPath。但这取决于您的应用程序从哪里开始。因此,如果您从 cmd 启动您的应用程序,我认为 python.exe 正在运行您的脚本。但是您的应用程序从您的脚本开始。所以试试脚本给脚本目录。

static string run_cmd(string arg) // arg value = image.png
{
    string result = ""; 
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = @"C:\Users\Sick\AppData\Local\Programs\Python\Python38-32\python.exe";//cmd is full path to python.exe
    start.Arguments = "Captchas/script.py " + arg;//args is path to .py file and any cmd line args
    start.UseShellExecute = false;
start.WorkingDirectory = ""//scriptPath
    start.RedirectStandardOutput = true;
    using (Process process = Process.Start(start))
    {
        using (StreamReader reader = process.StandardOutput)
        {
            result = reader.ReadToEnd();
            Console.WriteLine(result);
        }
    }
    return result;
}

有关更多信息,请访问此处:https ://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.workingdirectory?view=netcore-3.1


推荐阅读