今天對一隻程式進行壓力測試的時候,跑一個晚上發現Python 拋出這樣一個Exception:
IOError: [Errno 24] Too many open files:
這樣的問題很有可能就是某個地方沒有正確的釋放file handle
這時候如果可以知道當下握住哪些檔案就可以很容易知道是哪段程式碼有問題了
在此紀錄兩款方便的小工具
psutil (process and system utilities) 可以很簡單地透過程式碼列出當前開啟的檔案
import psutil
proc = psutil.Process()
print proc.open_files()
在windows作業系統上,也可以透過工具直接把該exe目前正在使用的檔案一次列出來
打開 Process explorer後,先切換至 View Handles


接著再選擇你想要觀察的程式,就可以發現這個程式當下握住那些檔案囉!

Chris 發表在 痞客邦 留言(0) 人氣(749)
在看開源碼的時候,很容易看到像這樣的function parameter,附帶一個星號的參數 *args ,或是附帶兩個星號的參數 **kwargs,這是python 裡面很常用的語法,可以讓python接收任意數量的參數
def foo(param1, *args, **kwargs): # 順序不可對調!!
pass
Chris 發表在 痞客邦 留言(1) 人氣(19,516)
曾經學過C++的,回頭過來看Python,可能就會誤認為Python 也有pass-by-value, pass by reference的概念就怕會不會因此在參數傳遞時產生大量不必要的運算量而拖慢了系統效能
Chris 發表在 痞客邦 留言(1) 人氣(12,225)
現在要來看一下map()函式的用法!!簡單看一下官方文件的簽名:https://docs.python.org/2/library/functions.html?highlight=map#map
- map(function, iterable, ...)
- Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
-
- 簡單的來說,就是定義一個function。接著用這個function來對一個iterable 的物件內每一個元素做處理,
- 光看文字可能還是很難懂,直接看例子吧~!!
我們可以輕易地使用map來對list裡面每一個元素的資料型態做轉換,
原本有一個資料型態為字串(str)的listA , 只要設定map函式第一個參數int ,第二個參數為要轉換的list
意思就是將list裡面的每一個元素都轉型成整數(int)
>>> listA = ['1','2','3']
>>> print map(int,listA)
[1, 2, 3]
當然,也可以自訂函式來做各種不一樣的運算
例如定義一個multiple2的函式,透過map我們就能夠對list每一個元素做 '乘2'
其實map這個函式的功能也能夠用list comprehensive 來達成。(第8行)
>>> def multiple2(x):
... return x*2
...
>>> list1 = [1,3,5,7,9]
>>> print map(multiple2,list1)
[2, 6, 10, 14, 18]
>>>
>>> print [multiple2(x) for x in list1]
[2, 6, 10, 14, 18]
map也可以同時接收多個list做處裡
下面宣告三組list,一個三個參數的函式 adder(x,y,z),加總後回傳。
理所當然的,也能夠使用list comprehensive來完成。(第11行)
>>> def adder(x,y,z):
... return x+y+z
...
>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>> list3 = [100,100,100,100,100]
>>>
>>> print map(adder,list1,list2,list3)
[103, 107, 111, 115, 119]
>>>
>>> print [adder(x,y,z) for x,y,z in zip(list1,list2,list3)]
[103, 107, 111, 115, 119]
Chris 發表在 痞客邦 留言(1) 人氣(60,622)