星期五, 8月 29, 2008

[Python]ftp之dir ls nlist and timeout

最近在用Python的ftplib,發現dir, ls, nlist有點差異,
dir等於ls的加強,可以dir -R
dir or ls與nlist最大的差別是dir or ls會回傳檔案或是目錄的資訊,而nlist只有檔案名稱
兩個還有一個差異,這是依照ftp server而有所不同,如果是沒有檔案或是目錄的時候,
dir or ls會回傳220 transfer complete.
nlist會回傳550 No files found.
所以nlist會出先exception,在判斷上會不太一樣,記錄一下,以免忘記。
--------------------------------------------------------------------
另外ftplib在Python 2.6之後才支援timeout的設定,那Python 2.6之前的怎麼辦呢?
可以用sock設定,下面是例子:
import socket
socket.setdefaulttimeout(5*60)
以秒為單位,自己決定設定多久timeout嚕~~~~^^

星期二, 8月 26, 2008

[管理]管理者的管理績效

http://cgi.blog.roodo.com/trackback/3429045

石頭大大的這一篇文章真是讓我體會良多啊,我本來就很不贊同工作時間長,可是其實是因為人性懶惰,所以效率才會低,對於效率高的人來說真的不需要工作時間長就能做好事情了。

[Linux]ps 欄位說明

USER 這個process的擁有者。
PID 這個process的編號,範圍0-65535。
%CPU 這個process現在佔用的CPU時間百分比。
%MEM 這個process現在佔用的虛擬記憶體(VM)百分比。
VSZ 這個process佔用的虛擬記憶體的大小(=DRAM+SWAP)
RSS 這個process佔用的真實記憶體的大小(DRAM)。

TTY 終端機編號。
STAT process目前的狀況。
R running
T stopped
I idle
P page wait
S sleep
TIME 這個process到目前為止,使用CPU的時間。
COMMAND process名稱或參數。

參考吧,不然每次都忘記,記憶力變差了。

星期一, 8月 25, 2008

[Python]subprocess

http://fannys23.pixnet.net/blog/post/15367167

http://mrwlwan.wordpress.com/2008/10/15/python%EF%BC%9A%E4%BD%BF%E7%94%A8-subprocess-%E8%B0%83%E7%94%A8%E5%A4%96%E9%83%A8%E5%91%BD%E4%BB%A4/

這邊有簡短的使用說明,根據我個人使用的經驗,
shell = True是執行shell的指令
shell = False是執行自己的程式
還有最好用
cmd = 'cat /a/b/c'
subprocess.call(cmd.split(), shell = True)

記得要用cmd.split()
我一開始就是忘記用.....>_< Update: 經過反覆的測試,發現我之前講錯了.....>_< shell = False 表示輸入需為sequence也就是list,然後不可以有特殊字元,例如regular expression,因為當shell = False 是用os.execvp()去執行child program,而regular expression是shell提供的功能,所以當shell = False,就沒有shell的功能,只能要執行什麼就執行什麼 例如: #!/usr/bin/env python import subprocess cmd = 'cat /etc/passwd' subprocess.call(cmd.split(), shell = False) 就會得到passwd的所有資料 但不能用cmd = 'cat /etc/*' 當shell = False會以為你要找的是 * 這個檔案 shell = True 如果input是string的話,表示把input丟到shell去執行,可以有regular expression也可以有分號 例如: #!/usr/bin/env python import subprocess cmd = 'cat /etc/*' subprocess.call(cmd, shell = True) 就會cat所有在etc下面的檔案內容 反正只要在shell下可以執行的,都可以寫在這 cmd = 'cat /etc/passwd | grep root' cmd = 'ls /etc/; ps axu' 如果input是sequence的話,我看不太懂....>_<
原文在這:
On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.

看有沒有高手解釋一下~~~~^^

另外可以用subprocess.Popen()
用subprocess.call()只有return code
用subprocess.Popen()則是可以接回執行結果
例如:
#!/usr/bin/env python
import subprocess
cmd = 'cat /etc/*'
result = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
(stdout, stderr) = result.communicate()
這個時候result是一個pipe
這時候就可以抓你要的執行結果

千萬注意一點,就是close_fds的設定
If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.
另外
* Popen raises an exception if the execution fails.
* the capturestderr argument is replaced with the stderr argument.
* stdin=PIPE and stdout=PIPE must be specified.
* popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen.

表示說原則上,你需要在Unix上面設定close_fds=TRUE,但在windows上設定close_fds=TRUE就不能redirect standard handle by setting stdin, stdout, stderr.

星期三, 8月 20, 2008

[Python]Threading

http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/
http://www.hacker.com.cn/article/view_14446.html
http://code.activestate.com/recipes/302746/
http://www.davidnaylor.co.uk/threaded-data-collection-with-python-including-examples.html

以上是我找到的Python關於Threading的文章,對於我在寫Python multi-thread上面還蠻有參考價值的,其實非常的簡單,只要寫好Thread Object,然後帶一個Queue的物件,然後把你要傳的東西put,任何東西都可以,然後Thread Object就會get,就可以做到multi-thread,個人認為Python的官方網站,基本上只是reference,沒有教學的範例,除非有寫過的人才有用,不然根本看不懂怎麼寫。

貼一下程式碼好了
import threading, Queue
    class ClientThread(threading.Thread):
        def run(self):
            while True:
            item=Pool.get()#這裡可以接任何東西
            if item != None:
                #do your work
                Pool.task_done()#告訴Queue工作完成
Pool = Queue.Queue(0)
for x in range(num_of_threads):
    ClientThread.start()#要開幾個threads
while (xxx):#條件式自己設定
    Pool.put(xxx)#Put item進去
Pool.join()#等到所有的job都做完

星期四, 8月 14, 2008

[Python] Get ip

http://www.artima.com/forums/flat.jsp?forum=181&thread=113874

這個一定要記一下,如何抓出目前機器的IP,我試過沒問題。
socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
不過我倒是不懂後面的[0][4][0]的意思....>_<

星期三, 8月 13, 2008

[Python] optparse

http://www.blogger.com/post-create.g?blogID=16042244
http://www.javaworld.com.tw/jute/post/view?bid=14&id=88875&sty=3

Ross Wan’s World!
上面寫的是非常詳細的用法
Google support GUI

這是關於寫command line時的參數檢查與設定,對於在linux或是習慣command line開發的人很有幫助~~~~
範例:
import sys
import optparse
import optparse_gui

def main():
usage = "usage: %prog [options] args"
if 1 == len( sys.argv ):
option_parser_class = optparse_gui.OptionParser
else:
option_parser_class = optparse.OptionParser

parser = option_parser_class( usage = usage, version='0.1' )
parser.add_option("-f", "--file", dest="filename", default = r'c:\sample.txt',
help="read data from FILENAME")
parser.add_option("-a", "--action", dest="action",
choices = ['delete', 'copy', 'move'],
help="Which action do you wish to take?!")
parser.add_option("-n", "--number", dest="number", default = 23,
type = 'int',
help="Just a number")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose",
help = 'To be or not to be? ( verbose )')

options, args = parser.parse_args()

print 'args: %s' % args
print 'options: %s' % options

if '__main__' == __name__:
main()

[Python] Logging system

http://docs.python.org/lib/module-logging.html
http://www.red-dove.com/python_logging.html

以上兩個link是Python的logging system,寫的算是詳細,
要注意的是%(asctime)-24s
這裡的24表示長度是24不滿的部份補空白,超過就以超原本的長度為主
第一個link裡有寫,不過要狠認真看
也可以做logging server,專門收所有的log,這倒是狠有意思....只要做service的,應該都要有一套這個,好追蹤。
當然網路斷線也沒關係,logging system有支援兩種以上的log,可以本機有log,也可以送到logging server,只是fail over的機制就得自己想了....
----------------------------------------------------------------------------
Update:
http://bytes.com/forum/thread23499.html
試了一下SMTPHandler,發現每一個error就寄一封信,原來要有MemoryHandler,這實在是太神奇了,一定要記下來,不然怎麼猜得到
----------------------------------------------------------------------------
Update:
後來發現這樣如果是發生Error要寄出email不可行,所以只好改用BufferingSMTPHandler
,有興趣可以參考以下link
http://www.red-dove.com/python_logging.html