You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何通过C# Process方法运行Python脚本时无法识别导入文件夹?

问题:C# Process调用Python脚本时出现ModuleNotFoundError

命令提示符直接运行Python脚本正常,但通过C#的Process方法运行时,提示找不到notebook_utils模块,无法识别Utils文件夹。


相关代码

Python脚本(sjq_defect_detection.py)

import os
import pathlib
import sys  # 原代码遗漏该导入,需补充

# sys.path.insert(0, os.getcwd())
sys.path.append("utils")
# sys.path.append( '.' )
sys.path.append("./utils")

#from notebook_utils import segmentation_map_to_image, to_rgb
print(f"Python script path : {pathlib.Path(__file__).parent.absolute()}")

from notebook_utils import segmentation_map_to_image, to_rgb

C#调用代码

public void runDefectInspection(string imageFolder, string model_path)  //passing image folder
{
    MessageEventArgs e = new MessageEventArgs();
    e.message = @"<<<<<<<< Script initiaited, please wati.... >>>>>>>>";
    ProcessStartInfo start = new ProcessStartInfo();
    Process process = new Process();

    start.FileName = g_pythonEXEPath;
    if (File.Exists(g_pythonAlgorythmScript))
    {
        if (File.Exists(start.FileName))
        {
            string arg = String.Format("--FileName \"{0}\"  --ModelPath \"{1}\"", imageFolder, model_path);

            start.Arguments = string.Format("\"{0}\" \"{1}\"", g_pythonAlgorythmScript, arg);

            log.Write("Python file : " + start.FileName + "Python parameters >>> " + start.Arguments);

            m.message = start.Arguments;
            sendPythonMessage(this, m);
            sendPythonMessage(this, e);

            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            start.RedirectStandardOutput = !start.UseShellExecute;
            start.RedirectStandardError = !start.UseShellExecute;

            process.StartInfo = start;

            process.EnableRaisingEvents = true;
            process.OutputDataReceived += SJW_Output;
            process.ErrorDataReceived += SJW_Error;
            process.Exited += new EventHandler(SJW_Exited);

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();
        }
        else
        {
            m.message = "Python executable not found : " + start.FileName;
            sendPythonMessage(this, m);
        }
    }
    else
    {
        m.message = "Algorythm file not found : " + g_pythonAlgorythmScript;
        sendPythonMessage(this, m);
    }
}

运行输出与报错

命令行直接运行输出

Python script path : c:\Users\Rose\Inference

C#调用时报错

<<<<<<<< Script initiaited, please wati.... >>>>>>>>
SJW Error :Traceback (most recent call last):
SJW Error :Traceback (most recent call last):
SJW Error :  File "C:\Users\Rose\Inference\sjq_defect_detection.py", line 18, in <module>
SJW Error :    from notebook_utils import segmentation_map_to_image, to_rgb
SJW Error :ModuleNotFoundError: No module named 'notebook_utils'
SJW Error :ModuleNotFoundError: No module named 'notebook_utils'
<<<<<<<< Script completed >>>>>>>>

项目文件夹结构

Inference/
├── sjq_defect_detection.py
Utils/
├── notebook_utils.py  # 原描述中拼写为notebook_uitls.py,推测为输入错误

解决方案

核心原因

命令行直接运行时,当前工作目录是脚本所在的Inference文件夹,相对路径utils能正确指向同级的Utils文件夹;但C#的Process默认工作目录是C#程序的运行目录,而非Python脚本所在目录,导致相对路径失效。

解决方法

方法1:Python脚本中使用绝对路径添加sys.path

基于脚本自身路径拼接Utils文件夹的绝对路径,避免依赖当前工作目录:

import os
import pathlib
import sys

# 获取脚本所在目录的绝对路径
script_dir = pathlib.Path(__file__).parent.absolute()
# 拼接同级Utils文件夹的绝对路径
utils_dir = os.path.join(script_dir, "../Utils")
sys.path.append(str(utils_dir))

print(f"Python script path : {script_dir}")
print(f"Added utils path: {utils_dir}")

from notebook_utils import segmentation_map_to_image, to_rgb

方法2:C#中设置Process的工作目录为Python脚本所在路径

在C#代码中,为Process指定工作目录为Python脚本的所在文件夹,确保相对路径和命令行运行时一致:

// 在设置start.Arguments之后添加以下代码
start.WorkingDirectory = Path.GetDirectoryName(g_pythonAlgorythmScript);

方法3:统一文件夹名称大小写(可选)

确保Python脚本中写的sys.path.append("utils")和实际文件夹名称Utils大小写一致(Windows系统不区分大小写,但部分环境可能受影响),统一为Utils或utils。


内容的提问来源于stack exchange,提问作者PCG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:10:32