通过QProcess调用conda中的python
V1:
QProcess p;
//python 的路径
//QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QProcessEnvironment env; //有时候要用这个空环境变量才行,否则可能会出现一些污染的问题
env.insert("PYTHONPATH", "D:/ProgramData/Anaconda3/envs/pytorch_cuda/Lib");
env.insert("PYTHONHOME", "D:/ProgramData/Anaconda3/envs/pytorch_cuda");
// QString mPathValue = env.value("PATH");
// mPathValue = ";";
// env.insert("PATH", mPathValue);
p.setProcessEnvironment(env);
QStringList params;
QString pythonPath = "D:/ProgramData/Anaconda3/envs/pytorch_cuda/python.exe";
// 要执行的文件
QString pythonScript = "C:/Users/Administrator/Desktop/AiTrainer/demo.py";
params << pythonScript << "sdfdsf" << "123456";
// 设置工作目录
p.setWorkingDirectory("C:/Users/Administrator/Desktop/AiTrainer");
p.start(pythonPath, params);
p.waitForFinished(-1);
QString p_stdout = p.readAll();
QString p_stderr = p.readAllStandardError();
qDebug() << p_stdout << p_stderr;
V2:
V2版本的主要想法是直接通过命令行来执行,灵感来源于Anaconda Prompt:
// 下面这段代码是从anaconda的命令行快捷方式找到的,本方法就是基于这个的。
// %windir%\System32\cmd.exe "/K" D:\ProgramData\Anaconda3\Scripts\activate.bat D:\ProgramData\Anaconda3
QString workDir = "D:/MyDesktop/json"; // 工作目录
QString pyFile = "main.py"; // python文件
QString condaRoot = R"(D:\ProgramData\Anaconda3)"; //conda的根目录
QString batPath = R"(D:\ProgramData\Anaconda3\Scripts\activate.bat)"; // conda脚本
QString actCmd = "activate pytorch_cpu"; // 激活conda环境的命令
QProcess p;
p.setWorkingDirectory(workDir);
QStringList params;
params << "/K" << batPath << condaRoot;
p.start("cmd.exe", params);
p.waitForStarted();
p.waitForReadyRead();
qDebug() << "cmd started" << p.readAllStandardOutput();
p.write((actCmd + "\r\n").toLatin1());
p.waitForReadyRead();
qDebug() << QString::fromUtf8(p.readAllStandardError()) << p.readAllStandardOutput();
p.write(QString("python %1\r\n").arg(pyFile).toUtf8());
p.waitForReadyRead();
qDebug() << QString::fromUtf8(p.readAllStandardError()) << p.readAllStandardOutput();
connect(&p, &QProcess::readyRead, [=, &p](){
qDebug() << "------>" << p.readAllStandardError() << p.readAllStandardOutput();
});
p.waitForFinished(5000);
参考
https://blog.csdn.net/weixin_31165655/article/details/112933961
https://blog.csdn.net/qq_45254369/article/details/125285966