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

 

相关文章
|
16天前
|
Web App开发 Java Linux
Linux之Shell基本命令篇
Linux之Shell基本命令篇
Linux之Shell基本命令篇
|
1月前
|
安全 Shell Linux
【Shell 命令集合 系统管理 】Linux 锁定终端 vlock命令 使用指南
【Shell 命令集合 系统管理 】Linux 锁定终端 vlock命令 使用指南
35 1
|
1月前
|
监控 Shell Linux
【Shell 命令集合 系统管理 】Linux 显示当前登录到系统的用户信息 who命令 使用指南
【Shell 命令集合 系统管理 】Linux 显示当前登录到系统的用户信息 who命令 使用指南
43 1
|
1月前
|
监控 Shell Linux
【Shell 命令集合 系统管理 】Linux 显示目前登入系统的用户信息 w命令 使用指南
【Shell 命令集合 系统管理 】Linux 显示目前登入系统的用户信息 w命令 使用指南
44 2
|
17天前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
1月前
|
存储 Shell Linux
【Shell 命令集合 系统管理 】Linux 修改用户的属性和配置 usermod命令 使用指南
【Shell 命令集合 系统管理 】Linux 修改用户的属性和配置 usermod命令 使用指南
32 1
|
1月前
|
搜索推荐 Shell Linux
【Shell 命令集合 系统管理 】Linux 管理用户配置文件 userconf命令 使用指南
【Shell 命令集合 系统管理 】Linux 管理用户配置文件 userconf命令 使用指南
37 2
|
5天前
|
存储 Shell 数据安全/隐私保护
ZooKeeper【基础知识 04】控制权限ACL(原生的 Shell 命令)
【4月更文挑战第11天】ZooKeeper【基础知识 04】控制权限ACL(原生的 Shell 命令)
25 7
|
5天前
|
Java Go PHP
开发语言漫谈-PHP
PHP即“Hypertext Preprocessor”
|
7天前
|
缓存 编译器 API
NumPy与其他语言(如C/C++)的接口实践
【4月更文挑战第17天】本文介绍了NumPy与C/C++的接口实践,包括Python与C/C++交互基础、NumPy的C API和Cython的使用。通过案例展示了如何将C++函数与NumPy数组结合,强调了内存管理、类型匹配、错误处理和性能优化的最佳实践。掌握这些技能对于跨语言交互和集成至关重要。