IT技术博客大学习 共学习 共进步

python执行系统命令的方法

ISADBA|FH.CN 2015-01-20 23:27:51 浏览 4,963 次

   一、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

   二、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 ']

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

   三、使用模块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()

   四、使用模块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 
    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

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

建议继续学习

  1. 配置Nginx+uwsgi更方便地部署python应用 (阅读 106,824)
  2. 如何成为Python高手 (阅读 54,823)
  3. python实现自动登录discuz论坛 (阅读 32,662)
  4. python编程细节──遍历dict的两种方法比较 (阅读 20,202)
  5. 每个程序员都应该学习使用Python或Ruby (阅读 17,742)
  6. 30分钟3300%性能提升――python+memcached网页优化小记 (阅读 13,582)
  7. 使用python爬虫抓站的一些技巧总结:进阶篇 (阅读 13,123)
  8. 我的PHP,Python和Ruby之路 (阅读 12,983)
  9. Python处理MP3的歌词和图片 (阅读 9,422)
  10. 关于使用python开发web应用的几个库总结 (阅读 8,404)