转 Python执行系统命令的方法
Python执行系统命令的方法
Python中执行系统命令常见方法有两种:
两者均需 import os
(1) os.system
# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -> exit_status
Execute the command (a string) in a subshell.
# 如果再命令行下执行,结果直接打印出来
>>> os.system('ls')
04101419778.CHM bash document media py-django video
11.wmv books downloads Pictures python
all-20061022 Desktop Examples project tools
(2) os.popen
# 该方法不但执行命令还返回执行后的信息对象
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
例如:
>>>tmp = os.popen('ls *.py').readlines()
>>>tmp
Out[21]:
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickle_recs.py ',
'make_db_shelve.py ',
'peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']
好处在于:将返回的结果赋于一变量,便于程序的处理。
(3) 使用模块subprocess
>>> import subprocess
>>> subprocess.call (["cmd", "arg1", "arg2"],shell=True)
获取返回和输出:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
(4) 使用模块commands模块
>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')
注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:
Traceback (most recent call last):
File "./test1.py", line 56, in <module>
main()
File "./test1.py", line 45, in main
fax.sendFax()
File "./mailfax/Fax.py", line 13, in sendFax
os.popen(cmd)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)
关于本文更多的延伸阅读地址:
http://zh-cn.how-to.mobi/index.php?id=89228
转 Python执行系统命令的方法的更多相关文章
- Python执行系统命令的方法 os.system(),os.popen(),commands
os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...
- Python执行系统命令的方法
Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) ...
- Python执行系统命令并获得输出的几种方法
[root@a upfc]# ./ffmpeg-linux64-v3.3.1 -i a.mp3 ffmpeg version N-86111-ga441aa90e8-static http://joh ...
- python 执行系统命令模块比较
python 执行系统命令模块比较 1.os.system模块 仅仅在子终端运行命令,返回状态码,0为成功,其他为失败,但是不返回执行结果 如果再命令行下执行,结果直接打印出来 >>> ...
- 提高python执行效率的方法
python上手很容易,但是在使用过程中,怎么才能使效率变高呢? 下面说一下提高python执行效率的方法,这里只是说一点,python在引入模块过程中提高效率的方法. 例如: 1.我们要使用os模块 ...
- windows linux 使用python执行系统命令并将结果保存到变量
最近需要用到os.system 发现不能赋值到变量 后查有更新的模块,如下: os.system os.spawn* os.popen* popen2.* commands.* 重新使用content ...
- python执行系统命令后获取返回值的几种方式集合
python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...
- Python执行系统命令:使用subprocess的Popen函数
使用subprocess的Popen函数执行系统命令 参考: http://blog.sina.com.cn/s/blog_8f01450601017dlr.html http://blog.csdn ...
- 使用python执行系统命令——subprocess
背景:subprocess是python官方推荐调用系统命令的模块 import subprocess subprocess最主要的两个方法/类: # 参数说明:stdin和stdout相当于一个管 ...
随机推荐
- iOS 通过storyboard设置UIView或者其他layer图层的圆角
通常我们给Button或者UIView添加圆角是通过如下代码进行实现的 self.button.layer.cornerRadius=10; 但是如果你是使用的故事版或者xib进行设计视图的话,实际上 ...
- [LOJ] #2360. 「NOIP2016」换教室
期望DP #include<iostream> #include<cstring> #include<cstdio> #include<cctype> ...
- 【android】安卓的权限提示及版本相关
Only dangerous permissions require user agreement. The way Android asks the user to grant dangerous ...
- Nordic Collegiate Programming Contest 2015 E. Entertainment Box
Ada, Bertrand and Charles often argue over which TV shows to watch, and to avoid some of their fight ...
- 【转】MySQL innodb_autoinc_lock_mode 详解 ,并发插入时主键冲突的解决方案
本文转载于 http://www.cnblogs.com/JiangLe/p/6362770.html innodb_autoinc_lock_mode这个参数控制着在向有auto_increment ...
- Linux学习-CentOS 7.x 预设启动的服务简易说明
这里 仅介绍几个很常见的 daemons 而已,更多的信息呢,就得要麻烦你自己使用 systemctl list-unit-files --type=service 去查询.底下的建议主要是针对 Li ...
- 在ie9下在textbox框里面输入内容按enter键会触发按钮的事件
问题 在ie下,如果存在有button标签,如果在textbox里面输入内容,按下enter键,则会触发第一个按钮的click事件,经过测试,在IE10以及以下的都存在这个问题 原因 浏览器默认行为不 ...
- luogu3469 [POI2008]BLO-Blockade
#include <iostream> #include <cstring> #include <cstdio> using namespace std; type ...
- 【转】LAMP网站架构方案分析【精辟】
[转]LAMP网站架构方案分析[精辟] http://www.cnblogs.com/mo-beifeng/archive/2011/09/13/2175197.html Xubuntu下LAMP环境 ...
- Django多变关联、增加数据、删除数据
建立表之间的关联关系: models.py里面对表的字段及外键关系的设置如下: from django.db import models # Create your models here. #出版社 ...