프로그래밍/C++

c++ system 함수 output 변수에 담아 전달 방법

소행성왕자 2021. 12. 8. 14:45

사용자 정의함수 먼저 선언해야 한다.

cpp.cpp

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
int main()
{
std::string res;
res = exec("python3 ./client.py example.jpeg");
std::cout << ">>output\n";
std::cout << res;
}

컴파일

$ g++ -o cpp cpp.cpp

client.py

# -*- coding: utf-8 -*-
import sys
import re
import base64
import json
import os
import io
import requests
#from dcfgrpc.api import dcf
import time
from PIL import Image
imgPath = sys.argv[1]
if __name__ == "__main__":
with open(imgPath, "rb") as f:
encoded_string = base64.encodestring(f.read()).decode("utf-8")
#encoded_string = base64.encodebytes(f.read()).decode("utf-8")
data = {"image": encoded_string}
json_data = json.dumps(data)
#print(json_data)
# HTTP
url = "http://127.0.0.1:8000/ocr/"
result = requests.post(url, data=json_data)
# DCF
#result = dcf(url="keti.asuscomm.com:32222", service="keti-ocr", arg=json_data.encode())
#print(result)
json_data = json.loads(result.text)
result = json_data
print(result['result'])

 

참고

std::cout 의 이중 콜론의 의미는 ?

http://daplus.net/c-%EC%95%9E%EC%97%90-%EB%B6%99%EC%9D%80-%EC%9D%B4%EC%A4%91-%EC%BD%9C%EB%A1%A0%EC%9D%98-%EC%9D%98%EB%AF%B8%EB%8A%94-%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C/

 

[c++] 앞에 붙은 이중 콜론“::”의 의미는 무엇입니까? - 리뷰나라

수정해야 할 클래스에서이 코드 줄을 찾았습니다. ::Configuration * tmpCo = m_configurationDB;//pointer to current db 그리고 이중 콜론이 클래스 이름 앞에 붙는 것이 정확히 무엇을 의미하는지 모르겠습니다.

daplus.net

https://stackoverflow.com/questions/52164723/how-to-execute-a-command-and-get-return-code-stdout-and-stderr-of-command-in-c

 

How to execute a command and get return code stdout and stderr of command in C++

Given the following answer (first c++11 answer): How do I execute a command and get the output of the command within C++ using POSIX? Here is the implementation for your convenience: #include <c...

stackoverflow.com