文件操做 / IOhtml
os.walk() 和 os.path.walk()python
1、os.walk()linux
函數聲明:os.walk(top,topdown=True,onerror=None)git
(1)參數top表示須要遍歷的頂級目錄的路徑。github
(2)參數topdown的默認值是「True」表示首先返回頂級目錄下的文件,而後再遍歷子目錄中的文件。當topdown的值爲"False"時,表示先遍歷子目錄中的文件,而後再返回頂級目錄下的文件。shell
(3)參數onerror默認值爲"None",表示忽略文件遍歷時的錯誤。若是不爲空,則提供一個自定義函數提示錯誤信息後繼續遍歷或拋出異常停止遍歷。json
返回值:函數返回一個元組,含有三個元素。這三個元素分別是:每次遍歷的路徑名、路徑下子目錄列表、目錄下文件列表。vim
2、os.path.walkpython3.x
函數聲明:os.path.walk(top,func,arg)api
(1)參數top表示須要遍歷的目錄路徑
(2)參數func表示回調函數,即對遍歷路徑進行處理的函數。所謂回調函數,是做爲某個函數的參數使用,當某個時間觸發時,程序將調用定義好的回 調函數處理某個任務。注意:walk的回調函數必須提供三個參數:第1個參數爲os.path.walk的參數arg,第2個參數表示目錄 dirname,第3個參數表示文件列表names。注意:os.path.walk的回調函數中的文件列表不和os.walk()那樣將子目錄和文件分 開,而是混爲了一攤,須要在回調函數中判斷是文件仍是子目錄。
(3)參數arg是傳遞給回調函數的元組,爲回調函數提供處理參數,arg能夠爲空。回調函數的第1個參數就是用來接收這個傳入的元組的。
參考: http://my.oschina.net/duhaizhang/blog/68202
輸入
input 和 raw_input
input返回的是數值類型: int 或 float
raw_input返回的是string類型
例子
>>> s = input('請輸入:') 請輸入:45 + 32 >>> s 77 >>> type(s) <type 'int'> >>> s = raw_input('請輸入:') 請輸入:45 + 32 >>> s '45 + 32' >>> type(s) <type 'str'>
Python三目運算符的實現
條件 and 表達式1 or 表達式2
例子:
>>> 1 > 0 and 'yes' or 'no' 'yes' 其餘語言的寫法對比: 1 > 0 ? 'yes' : 'no'
** 運算符 -- 至關於 power()函數
>>> 2 ** 1 # 2的一次方 2 >>> 2 ** 2 # 2的二次方 4 >>> 2 ** 3 # 2的三次方 8
妙用 ** 運算符 開根號
# 開根號2
>>> 2 ** (1.0/2)
1.4142135623730951
>>> 4 ** (1.0/2)
2.0
# 開根號3
>>> 8 ** (1.0/3)
2.0
注: 1/3, 只保留整數位, 也就是 1/3的結果是0
Python中的 <> 至關於 !=, 不等於 -- 不建議使用
>>> 2 <> 1 # 2 不等於 1 True
字符串
Python中, 單引號 雙引號 和 三單引號 三雙引號的區別
單引號 和 雙引號是同樣的, 括起來表示字符串
三單引號 和 三雙引號也是同樣的, 括起來會幫助咱們自動換行, 對於有多個 '\n'的字符串, 會清晰易懂
>>> s = '''hello, ... my ... name ... is ... Juggling.''' >>> s 'hello,\nmy\nname\nis\nJuggling.' >>> print s hello, my name is Juggling.
利用urllib2抓取網頁內容
>>> import urllib2 >>> f = urllib2.open('http://fanyi.youdao.com/openapi.do?keyfrom=zqhong&key=694644553&type=data&doctype=json&version=1.1&q=good') >>> f = urllib2.urlopen('http://fanyi.youdao.com/openapi.do?keyfrom=zqhong&key=694644553&type=data&doctype=json&version=1.1&q=good') >>> json_str = f.read()
利用Pygame播放mp3
>>> import pygame.mixer as mixer >>> mixer.init() >>> mixer.music.load('na.mp3') >>> mixer.music.play() -------------------------------------------------------- 方法介紹: pygame.init() 進行所有模塊的初始化, pygame.mixer.init() 或者只初始化音頻部分 pygame.mixer.music.load('xx.mp3') 使用文件名做爲參數載入音樂 ,音樂能夠是ogg、mp3等格式。載入的音樂不會所有放到內容中,而是以流的形式播放的,即在播放的時候纔會一點點從文件中讀取。 pygame.mixer.music.play()播放載入的音樂。該函數當即返回,音樂播放在後臺進行。 play方法還可使用兩個參數 pygame.mixer.music.play(loops=0, start=0.0) loops和start分別表明重複的次數和開始播放的位置。 pygame.mixer.music.stop() 中止播放, pygame.mixer.music.pause() 暫停播放。 pygame.mixer.music.unpause() 取消暫停。 pygame.mixer.music.fadeout(time) 用來進行淡出,在time毫秒的時間內音量由初始值漸變爲0,最後中止播放。 pygame.mixer.music.set_volume(value) 來設置播放的音量,音量value的範圍爲0.0到1.0。 pygame.mixer.music.get_busy() 判斷是否在播放音樂,返回1爲正在播放。 pygame.mixer.music.set_endevent(pygame.USEREVENT + 1) 在音樂播放完成時,用事件的方式通知用戶程序,設置當音樂播放完成時發送pygame.USEREVENT+1事件給用戶程序。 pygame.mixer.music.queue(filename) 使用指定下一個要播放的音樂文件,當前的音樂播放完成後自動開始播放指定的下一個。一次只能指定一個等待播放的音樂文件。 --------------------------------------------------------
關於id()方法
>>> i1 = 10 >>> i2 = 10 >>> id(i1) 28790912 >>> id(i2) 28790912 >>> f1 = 1.5 >>> f2 = 1.5 >>> id(f1) 28862112 >>> id(f2) 28862160 id()方法能夠獲得對象在內存中的位置, 相似於"指針" Python默認會緩衝Integer, 可是Float不會. 從上面能夠看出
關於.py, .pyc, .pyo文件
py是源程序 pyc是編譯後的程序 在執行python源程序時,python會自動將源程序編譯成爲pyc文件 pyo是優化編譯後的程序 python -O 源文件便可將源程序編譯爲pyo文件 如何將py編譯成pyc? 1. 只編譯一個py文件 import py_compile py_compile.compile(r'H:\game\test.py') 2. 對一個文件夾的全部py文件進行編譯 import compileall compileall.compile_dir(dirpath) 如何將py編譯優化成pyo? python -O -m py_compile file.py
關於3 < 4 < 5
3 < 4 < 5 ==> 至關於 3 < 4 and 4 < 5 >>> 3 < 4 < 5 True >>> 3 < 4 and 4 < 5 True
XML to JSON
import xmltodict, json o = xmltodict.parse('<a>text</a>') json.dumps(o)
pip -- A tool for installing and managing Python packages.
pip 是管理Python包的工具. 相似於 easy_install 1. 安裝pip $ wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py $ python get-pip.py 2. pip的使用 # 安裝第三方包 $ pip install simplejson # 升級第三方包 $ pip install --upgrade simplejson # 卸載第三方包 $ pip uninstall simplejson
Python按行讀取文件,如何去掉'\n'
for line in file.readlines(): line=line.strip('\n')
range()的用法 和 切片的用法差很少
# 從0開始, 不包括10 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 從5開始, 不包括10 >>> range(5, 10) [5, 6, 7, 8, 9] # 從0開始, 不包括10, 步長爲3 >>> range(0, 10, 3) [0, 3, 6, 9] # 從-10開始, 不包括-100, 步長爲-30 >>> range(-10, -100, -30) [-10, -40, -70] >>> range(10, 0, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Linux中使用Python模擬鍵盤按鍵
這裏以 ctrl + shifit + v爲例子 (個人系統中, ctrl + shift + v爲粘貼)
#!/usr/bin/env python #-*- coding: utf-8 -*- import virtkey v = virtkey.virtkey() # press按下 v.press_keycode(37) # ctrl v.press_keycode(50) # shift v.press_unicode(ord('v')) # v # 釋放按鍵 v.release_unicode(ord('v')) v.release_keycode(50) v.release_keycode(37)
這樣就有一個問題, 如何獲取 keycode?
方法1: $ showkey -k 注: 這個方法獲取的keycode須要 加8 方法2: $ xve 方法3: dmesg 注: 若是是特殊的keycode, 能夠經過這個方法 方法4: xmodmap -pke
執行系統命令和sleep
import os os.system('commond') example: os.system('ls') #執行ls命令 import time time.sleep(1) # 暫停1秒
Python中各進制的轉換
首先, Python中二進制, 八進制, 十六進制的表示
# 二進制 >>> 0b10 2 # 八進制 >>> 010 8 # 十六進制 >>> 0x10 16
各進制的轉換
#十進制轉換二進制 >>> bin(10) '0b1010' #十進制轉換十六進制 >>> hex(10) '0xa' #二進制轉換十進制 >>> int('1010',2) 10 #十六進制轉換十進制 >>> int('0xa',16) 10 #十六進制轉換二進制 >>> bin(0xa) '0b1010' #二進制轉換十六進制 >>> hex(0b1010) '0xa'
Python中, 對時間的處理
http://blog.csdn.net/xiaobing_blog/article/details/12591917
# 1. 時間戳轉字符串 --> 獲取當前的時間戳, 並格式化成特定的字符串 >>> import time >>> now = int(time.time()) >>> timeArray = time.localtime(now) >>> timeArray time.struct_time(tm_year=2014, tm_mon=8, tm_mday=25, tm_hour=16, tm_min=28, tm_sec=30, tm_wday=0, tm_yday=237, tm_isdst=0) >>> time.strftime('%Y-%m-%d %H:%M:%S', timeArray) '2014-08-25 16:28:30' # 2. 將字符串轉時間戳 >>> a = '2013-10-10 23:40:00' >>> timeArray = time.strptime(a, '%Y-%m-%d %H:%M:%S') >>> timeStamp = int(time.mktime(timeArray)) >>> timeStamp 1381419600
某年某月某日是星期幾
>>> import datetime >>> todate = datetime.datetime(2014, 9, 1) >>> todate datetime.datetime(2014, 9, 1, 0, 0) >>> todate.weekday() + 1 1 爲何須要加1, 查看文檔 weekday(...) Return the day of the week represented by the date. Monday == 0 ... Sunday == 6
命令行解析工具 getopt()的使用
預備知識:
文件: get.py 內容: #!/usr/bin/python #-*- coding: utf-8 -*- for arg in sys.args: print arg 調用get.py python get.py -o 123.txt --help file1 file2 結果: get.py -o 123.txt --help file1 file2 注: argv[0] --> 咱們python腳本的名字 後面纔是咱們帶的參數
實例分析:
import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'ho:', ['help', 'output=']) except getopt.GetoptError as err: print str(err) sys.exit(2) for o, a in opts: if o in ('-h', '--help'): print o, a sys.exit() if o in ('-o', '--output'): print o, a 解釋: 1. sys.argv[1:], 過濾掉第一個參數(由於它是執行腳本的名字, 不該算參數的一部分) 2. 短格式分析串'ho:', 其中, 'h'是開關選項, 不帶參數, 'o:'則表示改選項後面帶一個參數, 舉例: python example.py -h -o 123.txt 3. 長格式分析串列表: ['help', 'output=']. 同理, 'help'是開關選項, 不帶參數, 'output='後面帶參數. (後面有‘=’表示要帶參數) 分析: '-h -o file --help --output=out.txt file1 file2' 分析後, opts爲: [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out.txt')] args則爲: ['file1', 'file2']
httplib2的使用
# 1. 獲取httpli2.Http對象 import httplib2 h = httplib2.Http() Http這個class的 初始化方法 __init__: __init__(self, cache=None, timeout=None, proxy_info=<function proxy_info_from_environment>, ca_certs=None, disable_ssl_certificate_validation=False) 注: h = httplib2.Http('.cache') 這個意思是: 講緩衝保存在當前目錄下的 '.cache'目錄 # 2. 例子 -- To PUT some content to a server that uses SSL and Basic authentication 注: method都須要大寫, 好比"GET", "PUT" #!/usr/bin/env python #-*- coding: utf-8 -*- import httplib2 h = httplib2.Http('.cache') h.add_credentials('name', 'password') (resp, content) = h.request('https://example.org/chapter/2', 'PUT', body='This is text', headers={'content-type': 'text/html'}) # 例子 import httplib2 h = httplib2.Http('.cache') (resp, content) = h.request('http://bitworking.org/', 'GET') (resp, content) = h.request('http://bitworking.org/', headers={'cache-control': 'no-cache'}) 附錄: | request(self, uri, method='GET', body=None, headers=None, redirections=5, connection_type=None) | Performs a single HTTP request. | | The 'uri' is the URI of the HTTP resource and can begin with either | 'http' or 'https'. The value of 'uri' must be an absolute URI. | | The 'method' is the HTTP method to perform, such as GET, POST, DELETE, | etc. There is no restriction on the methods allowed. | | The 'body' is the entity body to be sent with the request. It is a | string object.
注: httplib2返回的 resp 和 content 分別是 response 和 content, 其中, response是字典, 能夠很方便的獲得結果, 好比 resp['status'] , 獲得狀態碼
Python自動補齊
https://github.com/itnihao/vimrc-python
注: 快捷鍵修改爲 ctrl + n
編輯 /home/akira/.vim/bundle/pydiction/after/ftplugin/python_pydiction.vim
找到 inoremap <silent> <buffer> <Tab>
修改爲: inoremap <silent> <buffer> <C-n>
import os
os.path.isfile('test.txt') #若是不存在就返回False
os.path.exists(directory) #若是目錄不存在就返回False
Python中執行系統命令的三種方法
# 第一種 system(command) -> exit_status 返回的是exit_status >>> import os >>> status = os.system('ls') >>> status 0 # 第二種 os.popen(command [, mode='r' [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object. >>> import os >>> result = os.popen('df -h') >>> result.read() 'Filesystem Size Used Avail Use% Mounted on\n/dev/sda1 # 第三種 commands - Execute shell commands via os.popen() and return status, output. 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. >>> import commands >>> commands.getstatusoutput('ls /home/akira/Documents') (0, 'mykeycode\nsearch_keyword.py\ntest.py') >>> commands.getoutput('ls /home/akira/Documents') 'mykeycode\nsearch_keyword.py\ntest.py' >>> commands.getstatus('/home/akira/Documents/mykeycode') '-rw-r--r-- 1 akira akira 12945 Aug 24 13:32 /home/akira/Documents/mykeycode'
Python中的 chr(), ord(), unichr()
# int轉char 例子: chr(65) --> 'A'
chr(...) chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256.
# char轉int 例子: ord('A') --> 65 ord(...) ord(c) -> integer Return the integer ordinal of a one-character string. # int轉unicode 例子: unichr(65) --> u'A' unichr(...) unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
Python中如何查看內置函數
import __builtin__ help(__builtin__)
Python中如何不換行輸出 --> 看內置函數print()的參數
print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. 注: 須要python3.x支持 # file 默認print輸出到標準輸出流屏幕, 不過這個是能夠更改的 注:須要close()這個 file-like object 否則 默認系統會先寫入緩衝 到緩衝必定大小纔會輸出 >>> fw = open('./hhh', 'w') >>> print('hello world!', file=fw) >>> fw.close() # sep 兩個value中間用什麼分隔。 默認是 space >>> print('hello','world', sep='1') hello1world # end 默認, 輸出的時候以'\n'結尾, 可是有的時候, 咱們不須要, 則能夠用 end=''替換 >>> print('hello', end='') hello>>> # flush, 當flush爲True時, 強制每次寫入數據時都刷新一次 # 注: 咱們不須要close fw就能夠看到咱們寫入的數據了 >>> fw = open('ggg', 'w') >>> print('jjj', file=fw, flush=True)
Python如何查詢函數, 和其餘幫助信息
# 1. 打印關鍵字 >>> help() help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print .... del global pass # 2. 查看相關話題 這裏以NONE爲例子 help> topics help> NONE # 3. 查詢全部可用模塊 help> modules Please wait a moment while I gather a list of all available modules... ANSI _random gdbm quopri BaseHTTPServer _sha genericpath random Bastion _sha256 getopt re .... _multiprocessing functools pylint zope _osx_support future_builtins pynotify _pyio gc pyquery # 4. 使用dir, 查看對象有什麼屬性 >>> dir('a') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 5. 查看當前做用域的名稱
>>> dir()
['GFileDescriptorBased', 'GInitiallyUnowned', 'GPollableInputStream', 'GPollableOutputStream', 'GstChildProxy', 'GstProxyPad', 'Person', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'bob', 'f', 'info', 'joe', 'keyword', 'p', 'str', 'sys']
sys模塊的經常使用方法
# 1. sys.argv 傳入參數 argv[0]爲Python腳本名 # 2. sys.path 模塊搜索路徑 path[0]爲當前腳本目錄 修改的話 能夠在 ~/.zshrc 或者 ~/.profile 中添加 export PYTHONPATH=/home/akira/Documents/Python/ # 3. 查看平臺 >>> sys.platform 'linux2' # 4. 查看Python版本 >>> sys.version '2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]' >>> sys.version_info sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0) # 5. 查看最大整數 >>> sys.maxint 9223372036854775807
re模塊
關於flags參數
解釋
Some of the functions in this module takes flags as optional parameters: I IGNORECASE Perform case-insensitive matching. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. X VERBOSE Ignore whitespace and comments for nicer looking RE's. U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale. This module also defines an exception 'error'. 使用: >>> import re >>> re.IGNORECASE (常數)
例子:
# re.IGNORECASE 忽略大小寫 >>> re.findall('[a-z]', 'abcABCtT', flags=re.IGNORECASE) ['a', 'b', 'c', 'A', 'B', 'C', 't', 'T']
在Python中使用ping
https://pypi.python.org/pypi/ping/0.2 pip install ping
方法介紹:
FUNCTIONS checksum(source_string) I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c do_one(dest_addr, timeout, psize) Returns either the delay (in seconds) or none on timeout. quiet_ping(dest_addr, timeout=2, count=4, psize=64) Send `count' ping with `psize' size to `dest_addr' with the given `timeout' and display the result. Returns `percent' lost packages, `max' round trip time and `avrg' round trip time. receive_one_ping(my_socket, id, timeout) Receive the ping from the socket. send_one_ping(my_socket, dest_addr, id, psize) Send one ping to the given >dest_addr<. verbose_ping(dest_addr, timeout=2, count=4, psize=64) Send `count' ping with `psize' size to `dest_addr' with the given `timeout' and display the result.
經常使用方法:
quiet_ping(dest_addr, timeout=2, count=4, psize=64)
返回值:
>>> ping.quiet_ping('127.0.0.1')
(0, 0.15997886657714844, 0.1087188720703125)
第一個數字'0': 丟失的包的個數; 第二個數字'0.15997886657714844': 最大使用使用; 第三個數字'0.1087188720703125': 平均使用時間
# ping一個不存在的地址 結果 max_time = None, avg_time = None
>>> ping.quiet_ping('1.1.1.1')
(100, None, None)
verbose_ping(dest_addr, timeout-3, count-4, psize=64)
>>> ping.verbose_ping('127.0.0.1')
ping 127.0.0.1 with ... get ping in 0.1800ms
ping 127.0.0.1 with ... get ping in 0.0880ms
ping 127.0.0.1 with ... get ping in 0.0839ms
ping 127.0.0.1 with ... get ping in 0.0830ms
注: 使用這個ping模塊, 須要root的權限執行。
否則, 會拋出以下錯誤
socket.error: Operation not permitted - Note that ICMP messages can only be sent from processes running as root.
實例代碼, 測試一個網段存活的ip
https://gist.github.com/zqhong/85828f78b11995bde1d7
pdb調試技巧
q 退出debug h 打印可用的調試命令 b 設置斷點,b 5 在第五行設置斷點 h command 打印command的命令含義 disable codenum 使某一行斷點失效 enable codenum 使某一行的斷點有效 condition codenum xxx 針對斷點設置條件 c 繼續執行程序,直到下一個斷點 n 執行下一行代碼,若是當前語句有函數調用,則不會進入函數體中 s 執行下一行代碼,可是s會進入函數 w 打印當前執行點的位置 j codenum 讓程序跳轉到指定的行 l 列出附近的源碼 p 打印一個參數的值 a 打印當前函數及參數的值 回車 重複執行上一行
注: 這裏使用的是 Python 2.7