Pyhton 学习总结 20 :执行系统命令
在Python中执行系统命令有os.system()、os.popen()、commands.getstatusoutput()、subprocess.Popen等
1、os.system()
Python中关于os.system的描述:
>>> import os
>>> help(os.system)
system(command) -> exit_status
Execute the command (a string) in a subshell.
os.system()的命令执行是在子shell中执行,返回的是执行的退出状态码
>>> import os
>>> returnCode = os.system('adb devices')
List of devices attached
>>> print returnCode
0
>>> print open('C://temp.txt', 'r').readlines() ['List of devices attached \n', '\n']
2、os.popen()
Python官方文档关于os.popen的描述
<SPAN style="FONT-FAMILY: 宋体; FONT-SIZE: 15px">os.popen(command[, mode[, bufsize]])
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. Availability: Unix, Windows. Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section. Changed in version 2.0: This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the _popen() function from the libraries provided with Windows. Newer versions of Python do not use the broken implementation from the Windows libraries.</SPAN>
使用管道执行命令,“返回值”是一个打开的文件对象,该文件对象里面是系统命令的“输出”。对其进行读取 read() 的操作可以看到执行的输出。
>>> import os
>>> returnCode = os.popen('adb devices')
>>> print returnCode
<open file 'adb devices', mode 'r' at 0x00B99C80>
>>> print returnCode.read()
List of devices attached
3、commands.getstatusoutput()
可以获得到返回值和输出,非常好用。
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
>>> 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'
4、subprocess.Popen
Python官方文档关于subprocess的描述
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as: os.system
os.spawn*
os.popen*
popen2.*
subprocess.call代替os.system
>>> import subprocess
>>> returnCode = subprocess.call('adb devices')
List of devices attached >>> print returnCode
0
>>>
subprocess.check_output代替os.popen
>>> import subprocess
>>> returnCode = subprocess.check_output('adb devices')
>>> print returnCode
List of devices attached
subprocess.Popen使用
stdout
>>> import subprocess
>>> sp = subprocess.Popen('adb devices', shell=True, stdout=subprocess.PIPE)
>>> print sp
<subprocess.Popen object at 0x00BB68F0>
>>> print sp.stdout.read()
List of devices attached
#!/usr/bin/env python
# -*- coding: utf-8 -*- a = int(raw_input())
b = int(raw_input()) print 'a + b = ', a+b
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
p =subprocess.Popen('python C://plus.py', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
p.stdin.write('4\n')
p.stdin.write('5\n')
print p.stdout.readline()
PS:
1、test.py中,'python C://plus.py'里的python是必须的,参见:http://blog.csdn.net/jq0123/article/details/7448589
2、test.py中,p.stdin.write('4\n')里的“\n”是必须的
Pyhton 学习总结 20 :执行系统命令的更多相关文章
- golang学习笔记20 一道考察对并发多协程操作一个共享变量的面试题
golang学习笔记20 一道考察对并发多协程操作一个共享变量的面试题 下面这个程序运行的能num结果是什么? package main import ( "fmt" " ...
- java中执行系统命令
java程序中执行系统命令猛击下面的链接看看你就知道怎么用了 http://blog.csdn.net/a19881029/article/details/8063758 http://wuhongy ...
- Java 执行系统命令
在Java中执行系统命令,主要是使用ProcessBuilder和Runtime.getRuntime().exec().而在这里主要是介绍两种方法的使用. 使用情景是在linux系统中,使用menc ...
- Python执行系统命令的方法 os.system(),os.popen(),commands
os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...
- 值得 Web 开发人员学习的20个 jQuery 实例教程
这篇文章挑选了20个优秀的 jQuery 实例教程,这些 jQuery 教程将帮助你把你的网站提升到一个更高的水平.其中,既有网站中常用功能的的解决方案,也有极具吸引力的亮点功能的实现方法,相信通过对 ...
- python基础之使用os.system来执行系统命令
今天我们来尝试使用python 的os.system来执行系统命令 可以使用如下方法: import osprint os.system('ping www.baidu.com') 输出的结果是:64 ...
- Python执行系统命令的方法
Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) ...
- Ext.Net学习笔记20:Ext.Net FormPanel 复杂用法
Ext.Net学习笔记20:Ext.Net FormPanel 复杂用法 在上一篇笔记中我们介绍了Ext.Net的简单用法,并创建了一个简单的登录表单.今天我们将看一下如何更好是使用FormPanel ...
- php非阻塞执行系统命令
大家都知道php调用系统命令常用的主要有以下几种方法: 如exec(), system(), passthru(), shell_exec() 这几个函数的用法在此不做说明,有需要的请查阅php相关手 ...
随机推荐
- 理解钩子Hook以及在Thinkphp下利用钩子使用行为扩展
什么是钩子函数 个人理解:钩子就像一个”陷阱”.”监听器”,当A发送一个消息到B时,当消息还未到达目的地B时,被钩子拦截调出一部分代码做处理,这部分代码也叫钩子函数或者回调函数 参考网上说法 譬如我们 ...
- Spring MVC过滤器-字符集过滤器(CharacterEncodingFilter)
spring的字符集过滤通过用于处理项目中的乱码问题,该过滤器位于org.springframework.web.filter包中,指向类CharacterEncodingFilter,Charact ...
- 细说jQuery原型的创建和实现原理,并用实例简单模仿
在解析jQuery实现机理之前,我们先总结一下几点知识,这些都是我学习路上遇到的坑,我跌倒过很多次,现在把它补上: 1)自定义构造函数,如下例: function person(){ this.nam ...
- HDU 1421 DP
搬寝室 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...
- 关于viewpoint的疑惑
问题: 为什么在手机上打开一个PC web页面,用手机打开一个宽度为980的固定布局页面,页面会默认缩放到刚好满屏显示,并不会出现横向滚动条? 一:设备像素和CSS像素区别 现代浏览器中实现缩放的方式 ...
- vmware启动虚拟机报“内部错误”的解决方法
最近换了Win8系统,结果vmware就报了如标题描述的错误,网上查了些资料,现将解决方法记录在此,以备查阅. 右键点击wmware程序图标,选择[属性],选择[兼容性]选项卡,勾选“以管理员身份运行 ...
- java客户端调用c#的webservice服务
此处使用到了CXF框架,可以使用以下坐标从maven仓库中获取相关jar包: <dependency> <groupId>org.apache.cxf</groupId& ...
- Python 脚本 监控数据库状态
打算用这个脚本通过zabbix 监控Mariadb的,无奈要等Mariadb完全上线才行,所以先写一个粗略大致功能的版本. #coding:utf-8 #author:shiyiwen #versio ...
- BizTalk 开发系列(四十一) BizTalk 2010 BAM 安装手记
使用64位系统可以支持更大的内存,现在服务器基本上都使用64位系统.微软从Windows Server 2008 R2开始服务器版的操作系统也只支持64位了,不过对于像BizTalk这种“繁杂的东西” ...
- jquery Jsonp 跨域访问
$(function () { $.ajax({ url: 'http://ihisuns.vicp.cc:8765/PcClient.aspx', data: { "ModuleName& ...