Python中执行系统命令常见方法有两种:

两者均需 import os

(1) os.system

# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息

system(command) -> exit_status
Execute the command (a string) in a subshell.

# 如果再命令行下执行,结果直接打印出来

1 >>> os.system('ls')
2 04101419778.CHM   bash      document    media      py-django   video
3 11.wmv            books     downloads   Pictures  python
4 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.

例如:

01 >>>tmp = os.popen('ls *.py').readlines()
02 >>>tmp
03 Out[21]:
04 ['dump_db_pickle.py ',
05 'dump_db_pickle_recs.py ',
06 'dump_db_shelve.py ',
07 'initdata.py ',
08 '__init__.py ',
09 'make_db_pickle.py ',
10 'make_db_pickle_recs.py ',
11 'make_db_shelve.py ',
12 'peopleinteract_query.py ',
13 'reader.py ',
14 'testargv.py ',
15 'teststreams.py ',
16 'update_db_pickle.py ',
17 'writer.py ']

好处在于:将返回的结果赋于一变量,便于程序的处理。

(3)  使用模块subprocess

1 >>> import subprocess
2 >>> subprocess.call (["cmd""arg1""arg2"],shell=True)

获取返回和输出:

1 import subprocess
2 = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
3 for line in p.stdout.readlines():
4     print line,
5 retval = p.wait()

(4)  使用模块commands模块

1 >>> import commands
2 >>> dir(commands)
3 ['__all__''__builtins__''__doc__''__file__''__name__''getoutput''getstatus','getstatusoutput''mk2arg''mkarg']
4 >>> commands.getoutput("date")
5 'Wed Jun 10 19:39:57 CST 2009'
6 >>>
7 >>> commands.getstatusoutput("date")
8 (0'Wed Jun 10 19:40:41 CST 2009')

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:

1 Traceback (most recent call last):
2   File "./test1.py", line 56, in <module>
3     main()
4   File "./test1.py", line 45, in main
5     fax.sendFax()
6   File "./mailfax/Fax.py", line 13, in sendFax
7     os.popen(cmd)
8 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

http://www.javaeye.com/topic/406623

Python执行系统命令的方法的更多相关文章

  1. Python执行系统命令的方法 os.system(),os.popen(),commands

    os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...

  2. 转 Python执行系统命令的方法

    传送门 Python执行系统命令的方法 http://www.linux-field.com/?p=15 Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.sys ...

  3. Python执行系统命令并获得输出的几种方法

    [root@a upfc]# ./ffmpeg-linux64-v3.3.1 -i a.mp3 ffmpeg version N-86111-ga441aa90e8-static http://joh ...

  4. python 执行系统命令模块比较

    python 执行系统命令模块比较 1.os.system模块 仅仅在子终端运行命令,返回状态码,0为成功,其他为失败,但是不返回执行结果 如果再命令行下执行,结果直接打印出来 >>> ...

  5. 提高python执行效率的方法

    python上手很容易,但是在使用过程中,怎么才能使效率变高呢? 下面说一下提高python执行效率的方法,这里只是说一点,python在引入模块过程中提高效率的方法. 例如: 1.我们要使用os模块 ...

  6. windows linux 使用python执行系统命令并将结果保存到变量

    最近需要用到os.system 发现不能赋值到变量 后查有更新的模块,如下: os.system os.spawn* os.popen* popen2.* commands.* 重新使用content ...

  7. python执行系统命令后获取返回值的几种方式集合

    python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...

  8. Python执行系统命令:使用subprocess的Popen函数

    使用subprocess的Popen函数执行系统命令 参考: http://blog.sina.com.cn/s/blog_8f01450601017dlr.html http://blog.csdn ...

  9. 使用python执行系统命令——subprocess

     背景:subprocess是python官方推荐调用系统命令的模块 import subprocess subprocess最主要的两个方法/类: # 参数说明:stdin和stdout相当于一个管 ...

随机推荐

  1. user is not in the sudoers file.This incident will be reported

    我用普通用户ssk登陆,想让ssk成为拥有超级用户的权限的普通用户 开始提示输入密码错误 ,然后就这样了   解决方法如下: 1>.进入超级用户模式.也就是输入"su -", ...

  2. SoapUI命令行方式运行

    http://stackoverflow.com/questions/9220132/soapui-groovy-script-calls-to-command-line SoapUI支持用命令行方式 ...

  3. IPv6 相关的工作简介

    这里说明下,仅仅是IPv6在开发板上的相关的工作简介,没有很详细,都是自己一边积累,一边实践的.能帮助其他人最好,也算是给自己做个备忘录. 一.首先说下DHCPv6相关的.这里我使用的是DHCP6s. ...

  4. MySQL中进行树状所有子节点的查询

    在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点.但很遗憾,在MySQL的目前版本中还没有对应的功能. ...

  5. JQuery动画插件Velocity.js发布:更快的动画切换速度

    5月3日,Julian在其GitHub上发布了Velocity.js.Velocity.js是一款动画切换的jQuery插件,它重新实现了jQuery的$.animate()方法从而加快动画切换的速度 ...

  6. git有merge时如何删除分支

    不小心增加了一个分支,并且有了merge,如何删除掉? 具有merge时不能切换分支 可以利用git stash命令 git rm controllers/InterfaceController.ph ...

  7. hdu 4739 Zhuge Liang's Mines 随机化

    Zhuge Liang's Mines Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.p ...

  8. 关于self.用法的一些总结

    转自:http://www.cocoachina.com/bbs/read.php?tid=12850&page=1 最近有人问我关于什么时候用self.赋值的问题, 我总结了一下, 发出来给 ...

  9. ubuntu13.04装配oracle11gR2

    http://jingyan.baidu.com/album/bea41d435bc695b4c41be648.html?picindex=2 http://www.360doc.com/conten ...

  10. 512字节纠错1位的ECC校验码生成演示

    Flash型号: NandFlash型号:TC58NVG2S3ETA00 pagesize: 2KB oobsize  : 64B blocksize : 128K 关于ECC可以参考:http:// ...