1.os.popen(command[, mode[, bufsize]])
os.system(command)
2.os.popen() 功能強於os.system() , os.popen() 可以返回回顯的內容,以文件描述符返回。
eg:
t_f = os.popen ("ping 192.168.1.1")
print t_f.read()
或者:
for line in os.popen("dir"):
print line
最近在做那個測試框架的時候發現 Python 的另一個獲得系統執行命令的返回值和輸出的類。
最開始的時候用 Python 學會了 os.system() 這個方法是很多比如 C,Perl 相似的。
|
|
但是這樣是無法獲得到輸出和返回值的,繼續 Google,之后學會了 os.popen()。
|
|
通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是怎么讀取程序執行的返回值呢,當然咯繼續請教偉大的 Google。Google 給我指向了 commands — Utilities for running commands。
這樣通過 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出,非常好用。
|
|
Python Document 中給的一個例子,很清楚的給出了各方法的返回。
|
|
|
os.system 調用系統命令,完成后退出,返回結果是命令執行狀態,一般是0 os.popen 可以實現一個“管道”,從這個命令獲取的值可以在python 中繼續被使用 os.popen使用語法如下: os.popen('CMD').readlines()[0] |
最近有個需求就是頁面上執行shell命令,第一想到的就是os.system,
os.system('cat /proc/cpuinfo')
但是發現頁面上打印的命令執行結果 0或者1,當然不滿足需求了。
嘗試第二種方案 os.popen()
output = os.popen('cat /proc/cpuinfo')
print output.read()
通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程序執行的返回值)
嘗試第三種方案 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出,非常好用。
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
Python Document 中給的一個例子,
>>> 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'
Python os.popen() Method
Description
The method popen() opens 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 in open() function.
Syntax
Following is the syntax for popen() method:
os.popen(command[, mode[, bufsize]])
Parameters
-
command -- This is command used.
-
mode -- This is the Mode can be 'r'(default) or 'w'.
-
bufsize -- If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Return Value
This method returns an open file object connected to the pipe.
Example
The following example shows the usage of popen() method.
# !/usr/bin/python import os, sys # using command mkdir a = 'mkdir nwdir' b = os.popen(a,'r',1) print b
When we run above program, it produces following result:
open file 'mkdir nwdir', mode 'r' at 0x81614d0
調用c程序:
fd=os.popen('/path/to/alignment arg1 arg2 arg3')
output=fd.read()
fd.close()
