python执行shell命令
来源:互联网 发布:康师傅 统一 知乎 编辑:程序博客网 时间:2024/04/20 08:39
最近有个需求就是页面上执行shell命令,第一想到的就是os.system,
复制代码代码如下:
os.system('cat /proc/cpuinfo')
但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。
尝试第二种方案 os.popen()
复制代码代码如下:
output = os.popen('cat /proc/cpuinfo')
print output.read()
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)
尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
复制代码代码如下:
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
Python Document 中给的一个例子,
复制代码代码如下:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
最后页面上还可以根据返回值来显示命令执行结果。
0 0
- python执行shell命令
- python执行shell命令
- python执行shell命令
- python执行shell命令
- python执行shell命令
- Python执行Shell命令
- python执行shell命令
- python中执行shell命令
- python中执行shell命令
- python的执行shell命令
- Python之执行shell命令
- Python 执行shell命令:system
- Python中执行shell命令的实例
- 获取python执行shell命令的结果
- Python执行Shell命令测试脚本
- 每天一篇python:执行shell命令
- python脚本执行shell命令或脚本
- Python脚本中执行shell命令
- layout_gravity 和 gravity以及对应值的详解
- VMware虚拟机从一台电脑转移复制到另一台电脑的方法
- Xcode6使用storyboard在TabBarController上建立三个以上Item
- 退出登陆的总结
- Norsar 3D v5.44 Linux 1CD(功能强大的正演软件)
- python执行shell命令
- mysql 对于一个库的备份和还原, 对于大数据量的快速备份和还原
- shell 13问
- 更新admob ios sdk GoogleAdMobAdsSdkiOS 时编译报错
- C++11类(1) 基础技巧 Class Basic
- JS面向对象的数据属性的用法
- declare-styleable中format详解
- 11--黑马程序员--技术总结之字符串
- Landmark EDM/EDT R5000.1.10.2