C++/Php/Python 语言执行shell命令

简介: 编程中经常需要在程序中使用shell命令来简化程序,这里记录一下。1. C++ 执行shell命令 1 #include 2 #include 3 #include 4 5 int exec_cmd(std::string cmd, std::string &res){ 6 if (cmd.

编程中经常需要在程序中使用shell命令来简化程序,这里记录一下。

1. C++ 执行shell命令

 1 #include <iostream>
 2 #include <string>
 3 #include <stdio.h>
 4 
 5 int exec_cmd(std::string cmd, std::string &res){
 6     if (cmd.size() == 0){   //cmd is empty 
 7         return -1;
 8     }
 9 
10     char buffer[1024] = {0};
11     std::string result = "";
12     FILE *pin = popen(cmd.c_str(), "r");
13     if (!pin) { //popen failed 
14         return -1;
15     }
16 
17     res.clear();
18     while(!feof(pin)){
19         if(fgets(buffer, sizeof(buffer), pin) != NULL){
20             result += buffer;
21         }
22     }
23 
24     res = result;
25     return pclose(pin); //-1:pclose failed; else shell ret
26 }
27 
28 int main(){
29     std::string cmd = "ls -ial";
30     std::string res;
31 
32     std::cout << "ret = " << exec_cmd(cmd, res) << std::endl;
33     std::cout << res << std::endl;
34 
35     return 0;
36 }

2. Php执行shell命令

1 <?php
2     $cmd = "wc -l ./test.php";
3     exec($cmd, $output, $code);
4 
5     echo $code."\n";
6     print_r($output);
7 ?>

3. Python执行shell命令

1 import commands
2 
3 status, output = commands.getstatusoutput('ls -lt')
4 
5 print status
6 print output

 

相关文章
|
2月前
|
C++ 计算机视觉 Python
我在Python中丢的面子被我用C++找回来了
我在Python中丢的面子被我用C++找回来了
26 0
|
2月前
|
存储 计算机视觉 异构计算
使用python&C++对bubbliiiing的yolo系列进行opencv.dnn进行推理部署
使用python&C++对bubbliiiing的yolo系列进行opencv.dnn进行推理部署
36 0
|
8天前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
26天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
154 0
|
14天前
|
C++ Python
【C++/Python】C++调用python文件
【C++/Python】C++调用python文件
|
26天前
|
XML 数据采集 数据格式
Python语言的结构化标志语言处理
Python语言的结构化标志语言处理
|
1月前
|
关系型数据库 数据库 C++
嵌入式数据库sqlite3【基础篇】基本命令操作,小白一看就懂(C/C++)
嵌入式数据库sqlite3【基础篇】基本命令操作,小白一看就懂(C/C++)
|
1月前
|
Java API PHP
多多关键字API php java Python
多多关键字API接口广泛应用于商家进行市场分析、竞品分析、关键词优化等场景。商家可以通过分析关键词数据,了解用户需求,制定针对性的营销策略,提高产品的曝光率和转化率。
|
2月前
|
Rust API Android开发
Python潮流周刊#4:Python 2023 语言峰会
Python潮流周刊#4:Python 2023 语言峰会
16 2
|
2月前
|
JavaScript 前端开发 C语言
Python 到底是强类型语言,还是弱类型语言?
Python 到底是强类型语言,还是弱类型语言?
16 2