Skip to content

Instantly share code, notes, and snippets.

@debemdeboas
Last active January 21, 2022 23:23
Show Gist options
  • Save debemdeboas/d72333c1bf4986aac4c9b1281bb3a1a4 to your computer and use it in GitHub Desktop.
Save debemdeboas/d72333c1bf4986aac4c9b1281bb3a1a4 to your computer and use it in GitHub Desktop.
Invoke subprocess and capture output
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <array>
const std::string InvokeSubprocess(const std::string strTargetSubprocess) {
std::array<char, 128> arBuffer;
std::string strResult;
/**
* Windows does not support popen and pclose,
* so they need to be changed to _popen and
* _pclose.
*/
#ifdef _WIN32
std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(strTargetSubprocess.c_str(), "r"), _pclose);
#else
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(strTargetSubprocess.c_str(), "r"), pclose);
#endif
if (!pipe) {
throw std::runtime_error("Could not open pipe to subprocess");
}
while(fgets(arBuffer.data(), arBuffer.size(), pipe.get()) != nullptr) {
strResult += arBuffer.data();
}
return strResult;
}
/* Example */
/* InvokeSubprocess("python -c \"print(True)\"") */
/* InvokeSubprocess("ls -l /dev/null") */
import subprocess
from typing import Tuple
def invoke_subprocess(command: str) -> Tuple[str, str]:
proc = subprocess.run(command, capture_output=True, shell=True)
return proc.stdout, proc.stderr
# Example
# print(invoke_subprocess('python -c "print(True)"'))
# print(invoke_subprocess('ls -l /dev/null'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment