在QT中获取Python脚本的输出

Get output from Python script in QT

本文关键字:脚本 输出 Python 获取 QT      更新时间:2023-10-16

我想运行用Python编写的脚本并从中获得所有输出。这是我的cpp代码

QProcess process;
process.setProcessChannelMode(QProcess::MergedChannels);
QString exe = "python script.py";
process.start(exe);
process.waitForFinished(-1);
QString output(process.readAllStandardOutput());
qDebug() << output << endl;

和my script.py

import sys
print("Hello world!")

奇怪的是,当我把"python script.py"改为"ping google.com"时,它就像一个魅力一样工作。我也检查了我的cmd,但似乎我的Python安装也很好。我哪里做错了?

[编辑1]回声%路径%

C:ProgramDataOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Windowssystem32configsystemprofile.dnxbin;C:Program FilesMicrosoft DNXDnvm;C:Program FilesMicrosoft SQL Server120ToolsBinn;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:Program Files (x86)SkypePhone;C:Program FilesMicrosoftWeb Platform Installer;C:Program Files (x86)Microsoft ASP.NETASP.NET Web Pagesv1.0;C:Program Files (x86)Windows Kits8.0Windows Performance Toolkit;C:Program FilesMicrosoft SQL Server110ToolsBinn;C:Program Files (x86)GtkSharp2.12bin;C:Program Filesnodejs;C:Program FilesGitcmd;C:Program Files (x86)Microsoft SDKsTypeScript1.0;C:UsersMichaAppDataLocalProgramsPythonPython35-32Scripts;C:UsersMichaAppDataLocalProgramsPythonPython35-32;C:NVPACKgradle-2.9bin;C:NVPACKapache-ant-1.8.2bin;C:NVPACKjdk1.8.0_77bin;C:NVPACKandroid-ndk-r12b;C:NVPACKandroid-sdk-windowsextrasandroidsupport;C:NVPACKandroid-sdk-windowsbuild-tools;C:NVPACKandroid-sdk-windowsplatform-tools;C:NVPACKandroid-sdk-windowstools;C:UsersMicha?AppDataLocalatombin;C:UsersMichaAppDataRoamingnpm;C:Program Files (x86)Microsoft VS Codebin 

您需要修改您的PATH环境变量。

如果您使用官方安装程序并接受默认安装位置,python可能会在例如C:/Python27, C:/Python35等位置。所以你需要添加这些路径,也可能是C:/Python27/Scripts

参见:什么是PATH和其他环境变量,以及如何设置或使用它们