python2.7执行Linux系统命令

http://blog.chinaunix.net/uid-16844903-id-57786.html

1·os.system
举例:
  1. In [34]: import os

  2. In [35]: os.system('ls /home')
  3. cacti nagios oracle roottest1 roottest2 test6 test7
  4. Out[35]: 0
优点:直接显示命令的输出和返回值
2·os.popen
举例:
  1. In [36]: os.popen('ls /home')
  2. Out[36]: <open file 'ls /home', mode 'r' at 0xeacf60>

  3. In [37]: os.popen('ls /home').read()
  4. Out[37]: 'cacti\nnagios\noracle\nroottest1\nroottest2\ntest6\ntest7\n'

  5. In [38]: file_tmp = os.popen('ls /home')

  6. In [39]: for i in file_tmp:
  7.    ....: print i
  8.    ....:
  9.    ....:
  10. cacti

  11. nagios

  12. oracle

  13. roottest1

  14. roottest2

  15. test6

  16. test7
优点:可以将命令的输出保存在变量中,然后以多种方式展示出来
3·commands.getstatusoutput
举例:
  1. In [40]: import commands

  2. In [41]: (status, output) = commands.getstatusoutput('ls /home')

  3. In [42]: print status
  4. 0

  5. In [43]: print output
  6. cacti
  7. nagios
  8. oracle
  9. roottest1
  10. roottest2
  11. test6
  12. test7

  13. In [44]: commands.getstatusoutput('ls /home')
  14. Out[44]: (0, 'cacti\nnagios\noracle\nroottest1\nroottest2\ntest6\ntest7')

优点:命令输出和返回值分开显示
help资料
FUNCTIONS
    getoutput(cmd)
        Return output (stdout or stderr) of executing cmd in a shell.
   
    getstatus(file)
        Return output of "ls -ld <file>" in a string.
   
    getstatusoutput(cmd)
        Return (status, output) of executing cmd in a shell.

In [45]: commands.getoutput('ls /home') 
Out[45]: 'cacti\nnagios\noracle\nroottest1\nroottest2\ntest6\ntest7'
In [48]: commands.getstatus('/bin/ls')
Out[48]: '-rwxr-xr-x 1 root root 91240 2010-03-01 /bin/ls'

你可能感兴趣的:(python2.7执行Linux系统命令)