python、C++获取dos窗口/cmd/pycharm Terminal命令返回详情
一、python获取
# coding=utf-8
import os
cmd = "ipconfig" # 命令体
# cmd = "nslookup www.baidu.com"
tmp = os.popen(cmd)
res = tmp.read() # 要用read()方法读取后才是文本对象
print(res)
tmp.close() # 需将对象关闭
我们在使用电脑的时候,一般有的问题处理都会用到DOS窗口,执行我们的代码
python 调用系统 cmd命令获取本机 ip地址,得到结果:
# coding=utf-8
import os
cmd = "ipconfig"
# cmd = "nslookup www.baidu.com"
tmp = os.popen(cmd)
res = tmp.read() # 要用read()方法读取后才是文本对象
print(res)
tmp.close() # 需将对象关闭
二、C++获取
2.1 system()
system函数在不同平台下都有实现,但是system函数无法获取cmd执行的结果
#include "stdafx.h"
/**
* @brief 通过system调用命令行
*/
void cmdSystem(const std::string& cmdLine) {
system(cmdLine.c_str());
}
int main(int argc, char* argv[])
{
std::string cmdLine(R"("echo Hello,World!")");
cmdSystem(cmdLine);
system("pause");
return 0;
}
2.2 _popen()
使用匿名管道执行cmd命令并获取执行结果
/**
* @brief 通过_popen调用命令行并获取输出结果
*/
std::string cmdPopen(const std::string& cmdLine) {
char buffer[1024] = { '\0' };
FILE* pf = NULL;
pf = _popen(cmdLine.c_str(), "r");
if (NULL == pf) {
printf("open pipe failed\n");
return std::string("");
}
std::string ret;
while (fgets(buffer, sizeof(buffer), pf)) {
ret += buffer;
}
_pclose(pf);
return ret;
}
int main(int argc, char* argv[])
{
std::string cmdLine(R"("echo Hello,World!")");
// cmdSystem(cmdLine);
std::string tmp=cmdPopen(cmdLine);
printf("the resule of cmd is %s", tmp.c_str());
system("pause");
return 0;
}
2.3 CreateProcess()
#include <windows.h>
/**
* @brief 通过CreateProcess调用命令行并获取输出结果
*/
std::string cmdProcess(const std::string& cmdLine) {
/* 创建匿名管道 */
SECURITY_ATTRIBUTES _security = { 0 };
_security.bInheritHandle = TRUE;
_security.nLength = sizeof(_security);
_security.lpSecurityDescriptor = NULL;
HANDLE hRead = NULL, hWrite = NULL;
if (!CreatePipe(&hRead, &hWrite, &_security, 0)) {
printf("创建管道失败,error code=%d \n", GetLastError());
}
/* cmd命令行转换为Unicode编码 */
int convLength = MultiByteToWideChar(CP_UTF8, 0, cmdLine.c_str(), (int)strlen(cmdLine.c_str()), NULL, 0);
if (convLength <= 0) {
printf("字符串转换长度计算出错\n");
}
std::wstring wCmdLine;
wCmdLine.resize(convLength + 10);
convLength = MultiByteToWideChar(CP_UTF8, 0, cmdLine.c_str(), (int)strlen(cmdLine.c_str()), &wCmdLine[0], (int)wCmdLine.size());
if (convLength <= 0) {
printf("字符串转换出错\n");
}
/* 创建新进程执行cmd命令并将结果写入到管道 */
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE; // 隐藏cmd执行的窗口
si.hStdError = hWrite;
si.hStdOutput = hWrite;
if (!CreateProcess(NULL,
&wCmdLine[0],
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi)) {
printf("创建子进程失败,error code=%d \n", GetLastError());
}
/* 等待进程执行命令结束 */
::WaitForSingleObject(pi.hThread, INFINITE);
::WaitForSingleObject(pi.hProcess, INFINITE);
/* 从管道中读取数据 */
DWORD bufferLen = 10240;
char *buffer =(char*)malloc(10240);
memset(buffer, '\0', bufferLen);
DWORD recLen = 0;
if (!ReadFile(hRead, buffer, bufferLen, &recLen, NULL)) {
printf("读取管道内容失败, error code=%d\n", GetLastError());
}
std::string ret(buffer);
/* 关闭句柄 */
CloseHandle(hRead);
CloseHandle(hWrite);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
free(buffer);
return ret;
}
int main(int argc, char* argv[])
{
std::string cmdLine(R"("ipconfig")");
// cmdSystem(cmdLine);
//std::string tmp=cmdPopen(cmdLine);
std::string tmp = cmdProcess(cmdLine);
printf("the resule of cmd is %s", tmp.c_str());
system("pause");
return 0;
}