• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python中执行shell命令的几个方法小结

python中执行shell命令的几个方法小结

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python执行shell命令,python shell命令,python调用shell命令,python shell清屏命令,python shell清屏等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

最近有个需求就是页面上执行shell命令,第一想到的就是os.system,
os.system('cat /proc/cpuinfo')
</div>
但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。

尝试第二种方案 os.popen()
output = os.popen('cat /proc/cpuinfo')
print output.read()
</div>
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)

尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
</div>
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'
</div>
最后页面上还可以根据返回值来显示命令执行结果。

</div>

您可能想查找下面的文章:

  • python中执行shell的两种方法总结
  • python中执行shell的两种方法总结
  • 日常整理python执行系统命令的常见方法(全)
  • 日常整理python执行系统命令的常见方法(全)
  • python执行shell获取硬件参数写入mysql的方法
  • python中执行shell命令的几个方法小结

相关文章

  • Python的Django框架中消息通知的计数器实现教程
  • 详解Python中for循环的使用
  • 用Python实现服务器中只重载被修改的进程的方法
  • python回调函数用法实例分析
  • python中日期和时间格式化输出的方法小结
  • 完美解决Python2操作中文名文件乱码的问题
  • 编写Python脚本来获取mp3文件tag信息的教程
  • 解读Python中degrees()方法的使用
  • 在Django中进行用户注册和邮箱验证的方法
  • Python 网络编程起步(Socket发送消息)

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python使用scrapy抓取网站sitemap信息的方法
    • Python制作Windows系统服务
    • Python自动化构建工具scons使用入门笔记
    • python 输出一个两行字符的变量
    • 12步教你理解Python装饰器
    • Python中异常重试的解决方案详解
    • python端口扫描系统实现方法
    • 使用Python从有道词典网页获取单词翻译
    • python实现代码行数统计示例分享
    • python实现用于测试网站访问速率的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有