简体   繁体   English

使用 QProcess 静默执行 CMD 命令

[英]Execute CMD Command with QProcess silently

I wanted to execute some cmd command and then save their result for further work.我想执行一些 cmd 命令,然后保存它们的结果以供进一步工作。 I used system() for my purposes but it doesn't work silently.我将 system() 用于我的目的,但它不能静默工作。 When system() executes my commands, a console window will appear.当 system() 执行我的命令时,会出现一个控制台 window。 I didn't want console windows to appear to the user.我不希望控制台 windows 出现在用户面前。 How can I overwrite the following function with qprocess to execute my cmd command silently?如何使用 qprocess 覆盖以下 function 以静默执行我的 cmd 命令?

bool MainWindow::CreateTemporaryFiles()
{
    QString command_description = "wmic logicaldisk get description > C:\\Users\\Test\\AppData\\Local\\Temp\\description.log";
    system(command_description.toStdString().c_str());

    QString command_device_name = "wmic logicaldisk get DeviceID > C:\\Users\\Test\\AppData\\Local\\Temp\\names.log";
    system(command_device_name.toStdString().c_str());

    QString command_free_space = "wmic logicaldisk get FreeSpace > C:\\Users\\Test\\AppData\\Local\\Temp\\space.log";
    system(command_free_space.toStdString().c_str());

    QString command_size = "wmic logicaldisk get size > C:\\Users\\Test\\AppData\\Local\\Temp\\size.log";
    system(command_size.toStdString().c_str());

    QString command_file_system = "wmic logicaldisk get FileSystem > C:\\Users\\Test\\AppData\\Local\\Temp\\file.log";
    system(command_file_system.toStdString().c_str());

    QString command_sysname = "wmic logicaldisk get SystemName > C:\\Users\\Test\\AppData\\Local\\Temp\\sysname.log";
    system(command_sysname.toStdString().c_str());

    return true;
}

You can use popen to run a command and get the output.您可以使用popen运行命令并获取 output。

You can find an example here .你可以在这里找到一个例子。

QProcess allows you to do that also. QProcess也允许您这样做。 QProcess docs explain how to do it. QProcess文档解释了如何做到这一点。 Several examples here . 这里有几个例子。

(Edited.) (已编辑。)

If you need direct Windows, you have a complete example in the docs .如果您需要直接 Windows, 文档中有完整的示例。

This was shown as example.这被显示为示例。

#include <stdio.h>

int main(void)
{
        FILE *pipein_fp, *pipeout_fp;
        char readbuf[80];

        /* Create one way pipe line with call to popen() */
        if (( pipein_fp = popen("ls", "r")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Create one way pipe line with call to popen() */
        if (( pipeout_fp = popen("sort", "w")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Processing loop */
        while(fgets(readbuf, 80, pipein_fp))
                fputs(readbuf, pipeout_fp);

        /* Close the pipes */
        pclose(pipein_fp);
        pclose(pipeout_fp);

        return(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM