python - 在 VS C++ 代码中显示 Python 脚本警告

标签 python c++ warnings

我编写了一个 Python 脚本,它是对在 Visual Studio 2013 上编写的大型 C++ 程序的扩展。这些脚本在程序上运行良好,我可以使用 system() 在项目中轻松调用它命令。但是,我的新任务是从该脚本中获取任何警告,并将其显示为 VS 项目 中的警告。我没有共享目录,python 脚本不需要项目中的 C++ 变量,脚本也没​​有返回变量。

我目前运行脚本的简单方式:

system("py C:\\Task4\\testing_functions.py");

我尝试使用 <python.h>库,但无法在不篡改配置选项和目录的情况下让它在现有项目上工作,这对公司的其他人来说是行不通的。有没有办法可以将 python 日志导出到 Visual Studio 可以读取和显示的报告中?

最佳答案

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

#include <windows.h>
#include <cstdint>
#include <deque>
#include <thread>

using namespace std;

int SystemCapture(
    string         CmdLine,    //Command Line
    string         CmdRunDir,  //set to '.' for current directory
    string&        ListStdOut, //Return List of StdOut
    string&        ListStdErr, //Return List of StdErr
    uint32_t&      RetCode)    //Return Exit Code
{
    int                  Success;
    SECURITY_ATTRIBUTES  security_attributes;
    HANDLE               stdout_rd = INVALID_HANDLE_VALUE;
    HANDLE               stdout_wr = INVALID_HANDLE_VALUE;
    HANDLE               stderr_rd = INVALID_HANDLE_VALUE;
    HANDLE               stderr_wr = INVALID_HANDLE_VALUE;
    PROCESS_INFORMATION  process_info;
    STARTUPINFO          startup_info;
    thread               stdout_thread;
    thread               stderr_thread;

    security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
    security_attributes.bInheritHandle = TRUE;
    security_attributes.lpSecurityDescriptor = nullptr;

    if (!CreatePipe(&stdout_rd, &stdout_wr, &security_attributes, 0) ||
        !SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0)) {
        return -1;
    }

    if (!CreatePipe(&stderr_rd, &stderr_wr, &security_attributes, 0) ||
        !SetHandleInformation(stderr_rd, HANDLE_FLAG_INHERIT, 0)) {
        if (stdout_rd != INVALID_HANDLE_VALUE) CloseHandle(stdout_rd);
        if (stdout_wr != INVALID_HANDLE_VALUE) CloseHandle(stdout_wr);
        return -2;
    }

    ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&startup_info, sizeof(STARTUPINFO));

    startup_info.cb = sizeof(STARTUPINFO);
    startup_info.hStdInput = 0;
    startup_info.hStdOutput = stdout_wr;
    startup_info.hStdError = stderr_wr;

    if (stdout_rd || stderr_rd)
        startup_info.dwFlags |= STARTF_USESTDHANDLES;

    // Make a copy because CreateProcess needs to modify string buffer
    char      CmdLineStr[MAX_PATH];
    strncpy_s(CmdLineStr, CmdLine.c_str(), MAX_PATH);
    CmdLineStr[MAX_PATH - 1] = 0;

    Success = CreateProcess(
        nullptr,
        CmdLineStr,
        nullptr,
        nullptr,
        TRUE,
        0,
        nullptr,
        CmdRunDir.c_str(),
        &startup_info,
        &process_info
        );
    CloseHandle(stdout_wr);
    CloseHandle(stderr_wr);

    if (!Success) {
        CloseHandle(process_info.hProcess);
        CloseHandle(process_info.hThread);
        CloseHandle(stdout_rd);
        CloseHandle(stderr_rd);
        return -4;
    }
    else {
        CloseHandle(process_info.hThread);
    }
    /*
    if (stdout_rd) {
        stdout_thread = thread([&]() {
            DWORD  n;
            const size_t bufsize = 1000;
            char         buffer[bufsize];
            for (;;) {
                n = 0;
                int Success = ReadFile(
                    stdout_rd,
                    buffer,
                    (DWORD)bufsize,
                    &n,
                    nullptr
                    );
                printf("STDERR: Success:%d n:%d\n", Success, (int)n);
                if (!Success || n == 0)
                    break;
                string s(buffer, n);
                printf("STDOUT:(%s)\n", s.c_str());
                ListStdOut += s;
            }
            printf("STDOUT:BREAK!\n");
        });
    }
    */
    if (stderr_rd) {
        stderr_thread = thread([&]() {
            DWORD        n;
            const size_t bufsize = 1000;
            char         buffer[bufsize];
            for (;;) {
                n = 0;
                int Success = ReadFile(
                    stderr_rd,
                    buffer,
                    (DWORD)bufsize,
                    &n,
                    nullptr
                    );
                printf("STDERR: Success:%d n:%d\n", Success, (int)n);
                if (!Success || n == 0)
                    break;
                string s(buffer, n);
                printf("STDERR:(%s)\n", s.c_str());
                ListStdOut += s;
            }
            printf("STDERR:BREAK!\n");
        });
    }

    WaitForSingleObject(process_info.hProcess, INFINITE);
    if (!GetExitCodeProcess(process_info.hProcess, (DWORD*)&RetCode))
        RetCode = -1;

    CloseHandle(process_info.hProcess);

    if (stdout_thread.joinable())
        stdout_thread.join();

    if (stderr_thread.joinable())
        stderr_thread.join();

    CloseHandle(stdout_rd);
    CloseHandle(stderr_rd);

    return 0;
}


std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
            result += buffer.data();
    }
    return result;
}

int main(int argc, char* argv[])
{
    int            rc;
    uint32_t       RetCode;
    string         ListStdOut;
    string         ListStdErr;

    cout << "STARTING.\n";

    rc = SystemCapture(
        "py C:\\Task4\\testing_functions.py",    //Command Line
        ".",                                     //CmdRunDir
        ListStdOut,                              //Return List of StdOut
        ListStdErr,                              //Return List of StdErr
        RetCode                                  //Return Exit Code
        );
    if (rc < 0) {
        cout << "ERROR: SystemCapture\n";
    }

    /*
    cout << "STDOUT:\n";
    cout << ListStdOut;


    cout << "STDERR:\n";
    cout << ListStdErr;

    cout << "Finished.\n";
    */

    cout << "Press Enter to Continue";
    cin.ignore();

    return 0;
}

这整个代码将输出所有内容,包括 STDOUTSTDERR,我已经注释掉了所有标准输出,因为我只想要警告。

关于python - 在 VS C++ 代码中显示 Python 脚本警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793399/

相关文章:

python - Python 的 property.getter 的用途是什么?

c++ - 如何在 C++ 中重新启动循环(在随机运行中查找唯一序列)

c - 如果使用函数,编译器会发出警告

g++ - 警告 "operation on <variable> may be undefined"

Python调用C DLL函数输出问题和restype

haskell - 阻止 GHC 警告我一个特定的缺失模式

python - 当我尝试使用 pika (python) 向 RabbitMQ 确认消息时发生错误 "unknown delivery tag"

python - 在 Spark\PySpark 中保存\加载模型的正确方法是什么

python - Flask-SqlAlchemy 邻接列表关系 backfref 意外错误

c++ - 链接源文件