Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向 輸出流和輸入流
目錄
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼 python轉義符 字符串格式化
Python第三天 序列 5種數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 if else條件判斷 for循環 while循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承 裝飾器
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向 輸出流和輸入流
Python第十二天 收集主機信息 正則表達式 無名分組 有名分組
Python第十四天 序列化 pickle模塊 cPickle模塊 JSON模塊 API的兩種格式
Python第十五天 datetime模塊 time模塊 thread模塊 threading模塊 Queue隊列模塊 multiprocessing模塊 paramiko模塊 fabric模塊
輸出流和輸入流
cat 12.rpm |ssh 192.168.2.6 "cat - >/tmp/12.rpm"
函數名:如果由多個單詞組成,第二個單詞的首字母應該大寫
類名:如果由多個單詞組成,每個單詞的首字母應該大寫
變量名:全部小寫或者單詞之間用下劃線
#!/usr/bin/python和#!/usr/bin/env python的區別
/usr/bin/env表示到$PATH環境變量去找python執行文件,如果當前系統有兩套python,那么不需要更改腳本內容
如果使用/usr/bin/python 絕對路徑,就需要更改腳本
bash也有這種用法:#!/bin/bash和#!/usr/bin/env bash
Python如何處理管道輸入輸出
Python處理命令行參數
OS.path對文件路徑的處理
逐步實現python版的wc命令
示例 1 #!/usr/bin/env python # -*- coding:utf-8 -*- #__author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import sys #sys.stdin 就是一個文件類,Linux里一切皆文件 #input = sys.stdin input保存為文件描述符對象,相當于一個類sys.stdin實例化為一個對象input #讀取input時候按ctrl+d終止輸入 input = sys.stdin def lineCount(f): n = 0 for i in f: n += 1 return n print lineCount(input)
從標準輸入讀取
示例 2 #!/usr/bin/env python # -*- coding:utf-8 -*- #__author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import sys fd = sys.stdin data = fd.read() sys.stdout.write(data+"\n") print "你好"
文件對象的方法:
f.read() 按ctrl+d終止輸入 ,f.read(10) 讀取文件的10個字符,再運行第二次讀取后10個字符,再運行第三次讀取后10個字符,以此類推
f.readline() //用while遍歷每一行
f.readlines() 與[i for i in f] //對文件每一行進行遍歷
f.write()
f.close()
輸出
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import os import sys import string import gc import sys print "hello world" sys.stdout.write("Hello world"+'\n') sys.stderr.write("Hello Error")
標準輸出和標準錯誤輸出
sys.stdout.write(str) :參數是字符串
sys.stderr.write(str):參數是字符串
print和stdout的區別
print通常是調用一個stdout對象的write方法
print會先進行格式轉換
print會在最后加上換行符,要加逗號才能屏蔽換行符
print >> f,和fd.write()的區別
fd.write()只能輸入字符串,輸入數字要先用str()函數轉換為字符串或者或者格式化("%d\n" % i)
print >> fd,可以直接輸入int
print >> fd,"Hello world, I'm writting to file",11,200,300,400,500
fd = open('tmp','w')
fd.write('123')
示例
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import os import sys with open('F:\ a.txt', 'a') as f: #以寫的方式打開 print >> f, "Hello world, I'm writting to file", 11 # 用print往文件描述符里寫內容,可以輸入數字 #等價于 f.write("Hello world, I'm writting to file: "+str(11)) # 用write不能輸入數字要先str函數轉換為字符串或者格式化("%d\n" % i) print >> sys.stderr, "Hello world, I'm writting to file", 11 # 向標準錯誤輸入內容
stderr和重定向
#!/usr/bin/env python import sys print >> sys.stderr, "I am going to stderr" sys.stdout.write("I am standard output\n") python print2stderr.py 2> /dev/null
#寫入到標準錯誤
print >> sys.stderr ,"Hello world, I'm writting to file",11,200,300,400,500 python xx.py 2>/dev/null 可以重定向
------------------------------------------------------
stdout的buffer
python命令的-u 選項
文件對象的.flush() 方法
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import os import sys import time for i in range(1,10): sys.stdout.write("str:%d\n" % i) time.sleep(1) sys.stdout.flush() # # python buffer.py | cat - # python -u buffer.py | cat - # -u表示不需要buffer
--------------------------------------------------
簡單的word count
day04:包名
wc:模塊名
wordCount:函數名
from day04 import wc
#!/usr/bin/env python # -*- coding:utf-8 -*- #__author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ from sys import stdin data = stdin.read() chars = len(data) words = len(data.split()) lines = data.count('\n') print "%(lines)s %(words)s %(chars)s" % locals() 或者 print "%(lines)s %(words)s %(chars)s" % {'lines':lines,'words':words,'chars':chars} #可以用管道符進行調用cat /etc/hosts |python wc.py
locals()返回一個字典對象,代表當前的變量情況
#!/usr/bin/python
import sys
data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')
print "%(lines)s %(words)s %(chars)s" % locals()
locals()返回一個字典對象,代表當前的變量情況
下面兩種方法都可以
print "%s %s %s " %(chars,words,lines)
print "%(lines)s %(words)s %(chars)s" % locals()
#!/usr/bin/env python # -*- coding:utf-8 -*- #__author__="huazai" """ 從標準輸入或參數讀取文件內容 Date:2016.08.12 """ #!/usr/bin/python import sys import os if len(sys.argv) < 2: data = sys.stdin.read() else : try: fn = sys.argv[1] except IndexError: print "please follow a argument at %s" % __file__ # __file__內置變量表示腳本名 sys.exit() if not os.path.exists(fn): print "%s is not exists" % fn sys.exit() with open(fn) as fd: data = fd.read() chars = len(data) words = len(data.split()) lines = data.count('\n') print "%(lines)s %(words)s %(chars)s" % locals() # print sys.argv 返回一個列表 ,argv本身是一個屬性
--------------------------------------------------------
optparse
真正的命令行參數,代替sys.argv[],比如 ls /etc/passwd -l,sys.argv[]只能獲取到參數的索引位置,但是準確位置無法獲取,
比如獲取-l參數,-l可以寫在前面又可以寫在后面
ls /etc/passwd -l ,ls -l /etc/passwd
OptionParser是一個類
-c、--chars:命令行選項
dest:為選項定義變量名,值characters就是’-c’選項的名字,同理,words就是‘-w’選項的名字,lines就是‘-l’選項的名字,每個選項就是一個變量,選項的值就是變量的值
default=False:characters的默認值False,意思是默認情況下命令不帶-c選項
help:選項的解釋說明部分
改寫wc程序
支持 -l -w -l選項
支持文件參數和管道輸入
多文件計算總行數
程序中使用函數
示例1 #!/usr/bin/env python # -*- coding:utf-8 -*- #__author__="huazai" """ 從標準輸入或參數讀取文件內容 Date:2016.08.12 """ from optparse import OptionParser import sys, os # parser = OptionParser() parser = OptionParser("Usage: %prog [file1] [file2]...") parser.add_option("-c", "--chars", dest="characters", action="store_true", default=False, help="only count characters", ) parser.add_option("-w", "--words", dest="words", action="store_true", default=False, help="only count words", ) parser.add_option("-l", "--lines", dest="lines", action="store_true", default=False, help="only count lines", ) options, args = parser.parse_args() # 返回選項字典 options是一個類 可以直接調用選項(options.words)和參數列表 print options, args, if not (options.characters or options.words or options.lines): options.characters, options.words, options.lines = True, True, True data = sys.stdin.read() chars = len(data) words = len(data.split()) lines = data.count('\n') if options.lines: print lines, if options.words: print words, if options.characters: print chars, 調用方式:cat /etc/passwd |python wc.py 示例2 #!/usr/bin/env python # -*- coding:utf-8 -*- # __author__="huazai" """ pycharm 使用指南 Date:2016.08.12 """ import sys import os from optparse import OptionParser def opt(): parser = OptionParser("Usage: %prog [option] [file1] [file2]") parser.add_option("-c", "--char", dest="chars", action="store_true", default=False, help="only count chars") parser.add_option("-w", "--word", dest="words", action="store_true", default=False, help="only count words") parser.add_option("-l", "--line", dest="lines", action="store_true", default=False, help="only count lines") options, args = parser.parse_args() return options, args def get_count(data): chars = len(data) words = len(data.split()) lines = data.count('\n') return lines, words, chars def print_wc(options, lines, words, chars, fn): if options.lines: print lines, if options.words: print words, if options.chars: print chars, print fn def main(): options, args = opt() if not (options.lines or options.words or options.chars): options.lines, options.words, options.chars = True, True, True if args: total_lines, total_words, total_chars = 0, 0, 0 for fn in args: if os.path.isfile(fn): with open(fn) as fd: data = fd.read() lines, words, chars = get_count(data) print_wc(options, lines, words, chars, fn) total_lines += lines total_words += words total_chars += chars elif os.path.isdir(fn): print >> sys.stderr, "%s: is a directory" % fn else: sys.stderr.write("%s: No such file or direcotry\n" % fn) if len(args) > 1: print_wc(options, total_lines, total_words, total_chars, 'total') else: data = sys.stdin.read() fn = '' lines, words, chars = get_count(data) print_wc(options, lines, words, chars, fn) if __name__ == '__main__': main() #main()函數不想讓其他模塊調用,不加if __name__ == '__main__':,那么import wc這個模塊的時候就會自動執行main()這個函數
注意:OptionParser不能使用-h選項,因為他內置了一個幫助選項,就是-h
parser.add_option("-h", "--host", # 改為-H ,‘--Host’
dest="host",
action="store",
default='127.0.0.1',
help="host address")
print "%s -h" % __file__
sys.exit(1)
不然會報錯:optparse.OptionConflictError: option -h/--host: conflicting option string(s): -h
系統中的wc命令用C語言寫
文章列表