python、C++获取dos窗口/cmd/pycharm Terminal终端命令返回详情

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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值