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

如何通过QProcess调用WSL自动运行shellScript.sh脚本?

解决方案:通过QProcess实现WSL Shell脚本自动执行

方案1:直接调用PowerShell + WSL(无需中间bat/ps1)

在按钮的点击槽函数中,直接构建PowerShell命令,实现打开窗口、进入WSL目录并执行脚本,同时保持窗口不关闭:

void YourWindowClass::on_runShellScript_clicked()
{
    // 获取脚本的Windows路径
    QString winScriptPath = QCoreApplication::applicationDirPath() + "/shellScript.sh";
    // 转换为WSL兼容的Linux路径(C盘对应/mnt/c,替换反斜杠为正斜杠)
    QString wslScriptDir = winScriptPath.replace(":/", "/mnt/").replace("\\", "/");
    wslScriptDir = wslScriptDir.left(wslScriptDir.lastIndexOf('/'));

    // 构建PowerShell命令:-NoExit保证执行后窗口不关闭
    QString psCmd = QString(R"(powershell.exe -NoExit -Command "wsl cd '%1'; ./shellScript.sh")").arg(wslScriptDir);

    // 启动独立进程,避免阻塞UI
    QProcess::startDetached(psCmd);
}

关键说明:

  • 必须将Windows路径转换为WSL识别的/mnt/[盘符]/...格式,否则WSL无法定位文件
  • -NoExit参数让PowerShell执行完成后保持窗口,方便查看输出
  • 如果脚本没有执行权限,可将./shellScript.sh替换为bash shellScript.sh,跳过权限检查

方案2:修复bat文件的QProcess调用问题

如果坚持使用之前的bat+ps1方案,需确保QProcess正确调用cmd并保持窗口:

void YourWindowClass::on_runBatchScript_clicked()
{
    QString batPath = QCoreApplication::applicationDirPath() + "/runPowerShellScript.bat";
    // 用cmd的/k参数执行bat后不关闭窗口
    QProcess::startDetached("cmd.exe", QStringList() << "/k" << batPath);
}

注意事项:

  • 若bat文件路径包含空格,需给路径添加双引号:QStringList() << "/k" << QString("\"%1\"").arg(batPath)
  • 检查bat/ps1中的路径是否正确转换为WSL格式,避免路径错误导致脚本无法执行

额外提示

  • 提前在WSL中给脚本添加执行权限:打开WSL终端,执行chmod +x /mnt/[对应路径]/shellScript.sh
  • 若默认WSL发行版不是你需要的,可在命令中指定发行版,比如wsl -d Ubuntu cd ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:27:18