在c#上运行带参数的python脚本,当在cmd上运行时崩溃,不

问题描述 投票:0回答:1

不知怎的,我运行了一个带参数的python脚本,在cmd上运行得很完美,但当我把它传给我的C#时,似乎它没有正确地传递参数。

Cmd的结果。

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)

谢谢!

python c# cmd cv2
1个回答
1
投票

你应该指定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.comen-usdotnetapisystem.diagnostics.processstartinfo.workingdirectory?view=netcore-3.1。

© www.soinside.com 2019 - 2024. All rights reserved.