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

为何Python相对路径在C#调用时失效,直接运行却正常?

问题根源:工作目录不匹配

这个问题的核心原因很直白:C#启动Python进程时,默认的工作目录是C#程序的运行目录,而不是你的Python脚本所在的目录。

你在CMD里直接跑脚本时,CMD的工作目录就是脚本所在的文件夹,所以./input.txt能定位到文件;用绝对路径时,不管工作目录在哪都能找到目标文件。但通过C#调用时,Python进程的工作目录是C#程序的位置,自然找不到脚本同目录下的input.txt。

解决方案一:设置Python进程的工作目录(推荐)

修改你的C#代码,给ProcessStartInfo加上WorkingDirectory属性,指定为Python脚本所在的目录即可。这样Python运行时的工作目录就和脚本目录一致,相对路径就能正常解析了。

修改后的C#代码示例:

using System;
using System.Diagnostics;
using System.IO;

class Program
{
    static void Main()
    {
        string pythonExePath = @"path-to-python.exe";
        string scriptPath = @"path-to-script.py";
        // 获取脚本所在的目录
        string scriptDirectory = Path.GetDirectoryName(scriptPath);

        var pi = new ProcessStartInfo
        {
            FileName = pythonExePath,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            Arguments = scriptPath,
            // 设置工作目录为脚本所在目录
            WorkingDirectory = scriptDirectory
        };

        using (var p = Process.Start(pi))
        using (var reader = p.StandardOutput)
        {
            var err = p.StandardError.ReadToEnd();
            var res = reader.ReadToEnd();
            Console.WriteLine(err);
            Console.WriteLine(res);
        }
    }
}
解决方案二:在Python脚本中使用动态绝对路径(无需修改C#)

如果不想改动C#代码,也可以修改Python脚本,让它自动获取自身所在的目录,然后拼接input.txt的路径——这样不管Python进程的工作目录是什么,都能精准找到目标文件。

修改后的Python代码示例:

import os

# 获取当前脚本的绝对路径所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接input.txt的完整路径
input_file_path = os.path.join(script_dir, 'input.txt')

with open(input_file_path) as f:
    print(f.read().strip())

两种方案都能解决问题,你可以按需选择:如果多个Python脚本都需要依赖同目录文件,方案二更通用;如果只是单个脚本的调用场景,方案一的C#配置更直接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:27:14