使用C#代码激活conda环境(或者手动打开cmd和从C#中打开有什么区别?)

2024-10-01 13:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用conda环境(dlwin36)在windows上运行gpu加速的python脚本。在

我正在尝试激活dlwin36并执行脚本:

1)激活dlwin36

2)设置KERAS_BACKEND=tensorflow

3)Pythonmyscript.py在

如果我在我的机器上手动打开cmd并写下:“activate dlwin36” 它起作用了。在

但当我尝试从c打开命令时,我得到:

激活不能被识别为内部或外部命令、可操作的程序或批处理文件

我尝试使用以下方法:

命令链接:

var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&python myscript.py";
Process.Start(start).WaitForExit();

(我测试了UseShellExecute、LoadUserProfile和WorkingDirectory的几个变体)

重定向标准输入:

^{pr2}$

(我测试了LoadUserProfile和WorkingDirectory的几个变体)

在这两种情况下,我得到了相同的错误。在

手动打开cmd和从c打开它似乎有区别。在


Tags: py命令脚本cmdbackendtensorflow变体手动
3条回答

如果这对将来的任何人都有帮助。我发现你必须从C:\drive运行激活。在

关键是要跑激活.bat在你的命令行.exe在做其他事情之前。在

// Set working directory and create process
var workingDirectory = Path.GetFullPath("Scripts");
var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "cmd.exe",
        RedirectStandardInput = true,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        WorkingDirectory = workingDirectory
    }
};
process.Start();
// Pass multiple commands to cmd.exe
using (var sw = process.StandardInput)
{
    if (sw.BaseStream.CanWrite)
    {
        // Vital to activate Anaconda
        sw.WriteLine("C:\\PathToAnaconda\\anaconda3\\Scripts\\activate.bat");
        // Activate your environment
        sw.WriteLine("activate your-environment");
        // Any other commands you want to run
        sw.WriteLine("set KERAS_BACKEND=tensorflow");
        // run your script. You can also pass in arguments
        sw.WriteLine("python YourScript.py");
    }
}

// read multiple output lines
while (!process.StandardOutput.EndOfStream)
{
    var line = process.StandardOutput.ReadLine();
    Console.WriteLine(line);
}

你需要使用python.exe从你的环境中。例如:

Process proc = new Process();
proc.StartInfo.FileName = @"C:\path-to-Anaconda3\envs\tensorflow-gpu\python.exe";

或者在你的情况下:

^{pr2}$

相关问题 更多 >