天天看點

python子產品—command and sys

1.commands子產品

linux系統環境下用于支援shell的一個子產品

1)getoutput()

  傳回值隻有傳回結果(字元串類型),沒辦法判斷執行結果是否正常

例子

import commands

cmd = "ls /data/temp"

result1 = commands.getoutput(cmd)

print(type(result1))                   # 類型為str

print(result1)

結果:

<type 'str'>

2.py

2)getstatusoutout()

  傳回結果是一個tuple元組,第一個值為接收狀态碼,int類型,0表示正常,非0表示異常;第二個值為字元串,即shell指令執行的結果

cmd = "ps -ef"

status,result2 = commands.getstatusoutput(cmd)

print(type(status))

print(status)

print(type(result2))

print(result2)

<type 'int'>

UID         PID   PPID  C STIME TTY          TIME CMD

root          1      0  0 Oct09 ?        00:00:14 /usr/lib/systemd/systemd --switched-root --system --deserialize 21

root          2      0  0 Oct09 ?        00:00:00 [kthreadd]

2.sys子產品

1)通過sys子產品擷取程式參數

sys.argv[0]:第一個參數,腳本本身

sys.argv[1]:第二個參數,傳入的第一個參數

import sys

print("argv[0]={0}   argv[1]={1}".format(sys.argv[0],sys.argv[1]))

argv[0]=C:/Users/test/PycharmProjects/a/a1.python.py    argv[1]=parameter1

2)sys.stdin、sys.stdout、sys.stderr

  stdin、stdout、stderr 變量包含與标準I/O流對應的流對象。如果需要更好地控制輸出,而print 不能滿足你的要求,你也可以替換它們,重定向輸出和輸入到其它裝置( device ),或者以非标準的方式處理它們

例子1:sys.stdout與print

sys.stdout.write("hello"+ "\n")

print("hello")

hello

例子2:sys.stdin與raw_input

name1 = raw_input("input your name: ")

print(name1)

print 'stdin_your_name: ',        # command to stay in the same line

name2 = sys.stdin.readline()[:-1]     # -1 to discard the '\n' in input stream

print(name2)

input your name: huangzp

huangzp

stdin_your_name: huangzp

例子3: 控制台重定向檔案

f_hander = open("out.log","w")

sys.stdout = f_hander

結果:

本地生成一個out.log檔案,内容為hello

3)捕獲sys.exit(n)調用

  執行到主程式末尾,解釋器自動退出,但如需中途退出程式,可以調用sys.exit函數,帶有一個可選的整數參數傳回給調用它的程式,表示你可以在主程式中捕獲對sys.exit的調用。(0是正常退出,其他為異常)

def exitfunc():

   print "hello world"

sys.exitfunc = exitfunc   # 設定捕獲時調用的函數

print "start"

sys.exit(1)               # 退出自動調用exitfunc()後,程式退出

print "end"             # 不會執行print

start

hello world

說明:

  設定sys.exitfunc函數,及當執行sys.exit(1)的時候,調用exitfunc函數;sys.exit(1)後面的内容就不會執行了,因為程式已經退出

本文轉自 huangzp168 51CTO部落格,原文連結:http://blog.51cto.com/huangzp/1980367,如需轉載請自行聯系原作者