文章出處

Python第十天   print >> f,和fd.write()的區別    stdout的buffer  標準輸入 標準輸出  標準錯誤   重定向

 

 

目錄

Pycharm使用技巧(轉載)

Python第一天 安裝 shell 文件

Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼

Python第三天 序列 數據類型 數值 字符串 列表 元組 字典

Python第四天 流程控制 ifelse條件判斷 forwhile循環

Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數

Python第六天 類型轉換

Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫

Python第八天 模塊 包 全局變量和內置變量__name__ Python path

Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承

Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向

Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊

Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組

Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊

Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式

 

 


函數名:如果由多個單詞組成,第二個單詞的首字母應該大寫
類名:如果由多個單詞組成,每個單詞的首字母應該大寫
變量名:全部小寫或者單詞之間用下劃線

 

#!/usr/bin/python和#!/usr/bin/env python的區別
/usr/bin/env表示到$PATH環境變量去找python執行文件,如果當前系統有兩套python,那么不需要更改腳本內容
如果使用/usr/bin/python 絕對路徑,就需要更改腳本

 


Python如何處理管道輸入輸出
Python處理命令行參數
OS.path對文件路徑的處理
逐步實現python版的wc命令

示例 1
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
input = sys.stdin
def lineCount(f):
n = 0
for i in f:
n += 1
return n

print lineCount(input)

 

從標準輸入讀取

示例 2
#!/usr/bin/python
#coding:utf8

import sys
fd = sys.stdin
data = fd.read()
sys.stdout.write(data+"\n")
print "你好"

 


文件對象的方法:
f.read()
f.readline() //用while遍歷每一行
f.readlines() 與[i for i in f] //對文件每一行進行遍歷
f.write()
f.close()

 

輸出
#!/usr/bin/env python

import sys

print “hello world”
sys.stdout.write(“Hello world”)
sys.stderr.write(“Hello Error”)

 

 

輸出
#!/usr/bin/env python

import sys

print “hello world”
sys.stdout.write(“Hello world”)
sys.stderr.write(“Hello Error”)

print和stdout的區別
print通常是調用一個stdout對象的write方法
print會先進行格式轉換
print會在最后加上換行符,要加逗號才能屏蔽換行符


示例
#!/usr/bin/python

f = open('tmp','w')
print >> f,"Hello world, I'm writting to file",11,200,300,400,500
f.close()

 

-------------------------------------------------------------
print >> f,和fd.write()的區別
fd.write()只能輸入字符串write('123')不能輸入int write(123) 報錯
print >> f,可以直接輸入int
print >> f,"Hello world, I'm writting to file",11,200,300,400,500
fd = open('tmp','w')
fd.write('123')

 

 


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
#!/usr/bin/python

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

 

格式化字符串:"str:%d\n" % i

 

--------------------------------------------------

簡單的word count

day04:包名
wc:模塊名
wordCount:函數名
from day04 import wc

#!/usr/bin/python

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()

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/python

import sys
import os

try:
fn = sys.argv[1]
except IndexError:
print "please follow a argument at %s" % __file__
sys.exit()
if not os.path.exists(fn):
print "%s is not exists" % fn
sys.exit()
fd = open(fn)
data = fd.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')

print "%(lines)s %(words)s %(chars)s" % locals()

 

 

 

--------------------------------------------------------
optparse
真正的命令行參數,代替sys.argv[]

-c、--chars:命令行選項
dest:為選項定義變量名,值characters就是’-c’選項的名字,同理,words就是‘-w’選項的名字,lines就是‘-l’選項的名字,每個選項就是一個變量,選項的值就是變量的值
default=False:characters的值False,意思是默認情況下命令不帶-c選項
help:選項的解釋說明部分

 

示例1
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()
if not (options.characters or options.words or options.lines):
    options.characters, options.words, options.lines = True, True, True

示例2
#!/usr/bin/env python

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()

 

 

 

 

系統中的wc命令用C語言寫

 


文章列表


不含病毒。www.avast.com
文章標籤
全站熱搜
創作者介紹
創作者 AutoPoster 的頭像
AutoPoster

互聯網 - 大數據

AutoPoster 發表在 痞客邦 留言(0) 人氣(313)