顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

function 參數先排位置再對參數名稱

如果沒有指定要丟的參數名稱, python 就會照順序排. 如果順序對不起來就會 error.
>>> def f(a,b,c):
 print 'a:', a, 'b:', b, 'c:', c

 
>>> f(1,2,3)
a: 1 b: 2 c: 3
>>> f(1,c=3,b=2)
a: 1 b: 2 c: 3
>>> f(1,2,c=3)
a: 1 b: 2 c: 3
>>> f(1,2,b=2) # 第二個參數已經指定了, 所以就不能再指定 b

Traceback (most recent call last):
  File "", line 1, in 
    f(1,2,b=2)
TypeError: f() got multiple values for keyword argument 'b'

>>> f(c=3,2,a=1)
SyntaxError: non-keyword arg after keyword arg

>>> f(a=1,2,3)
SyntaxError: non-keyword arg after keyword arg

tuple 就是不可變的 list

tuple 就是不可變的 list.
>>> list = ['c',[1,2,3]]
>>> tuple = ('c',(1,2,3))
>>> list[0]
'c'
>>> list[1]
[1, 2, 3]
>>> tuple[0]
'c'
>>> tuple[1]
(1, 2, 3)
>>> list[0] = 'q'
>>> list[0]
'q'
>>> list[1]
[1, 2, 3]
>>> tuple[0] = 'q'

Traceback (most recent call last):
  File "", line 1, in 
    tuple[0] = 'q'
TypeError: 'tuple' object does not support item assignment

function is an object

python 的 function 是一個物件, 所以可以放進 collection 中等以後被呼叫.
>>> def a():
 print 'a';

 
>>> def b():
 print 'b';

 
>>> def c():
 print 'c';

 
>>> list = [a,b,c];
>>> for f in list:
 f();

 
a
b
c

split large file

I use Notepad++ to check log and debug.
When log file is large, I need to split large file to smaller ones.
I can't find tool so write codes to split file in Java every time.
I use Python to write a tool to split file when studying python.
Welcome to use this tool if you also need to split large log file.

python find pid by listen port

Codes

import sys
import subprocess
import shlex
import re

def find_pid_by_listen_port(port):
    if sys.platform == 'win32':
        output = subprocess.check_output('netstat -a -n -o', universal_newlines=True)
        match = re.search('.*:{0} +.* +.+ +[0-9]+'.format(port),output)
        if match:
            return shlex.split(match.group(0))[-1]
        else:
            return None
    else:
        raise Exception('not support platform ' + sys.platform)
    
pid = find_pid_by_listen_port(9160)
print(pid)

python download Cassandra and start up in Windows

Description

This program will kill existing Cassandra before deploy new one.

Codes

import os
import shutil
import sys
import math
import urllib.request
import subprocess
import shlex
import signal
import time
import re
from datetime import date

def http_download(download_url, download_file):
    with urllib.request.urlopen(download_url) as f:
        with open(download_file,'wb') as target:
            filesize = int(f.getheader('Content-Length'))
            wrotesize = 0
            while True:
                if wrotesize == int(filesize):
                    break
                wrotesize += target.write(f.read(1024))
                download_percent = math.ceil((wrotesize/filesize)*100)
                print('\rDownload {0} to {1} ... {2}%'.format(download_url,download_file,download_percent),end='')
    print()

def find_pid_by_listen_port(port):
    if sys.platform == 'win32':
        output = subprocess.check_output('netstat -a -n -o', universal_newlines=True)
        match = re.search('.*:{0} +.* +.+ +[0-9]+'.format(port),output)
        if match:
            return shlex.split(match.group(0))[-1]
        else:
            return None
    else:
        raise Exception('not support platform ' + sys.platform)
    
    
download_url = 'http://ftp.tc.edu.tw/pub/Apache/cassandra/2.0.4/apache-cassandra-2.0.4-bin.tar.gz'
download_file = 'd:/apache-cassandra-2.0.4-bin.tar.gz'
unzip_folder = 'd:/deploy/work/{0}/apache-cassandra-2.0.4-bin'.format(date.today().isoformat())
execute_folder = unzip_folder + '/apache-cassandra-2.0.4'
execute_path = execute_folder + '/bin/cassandra.bat'
executable = 'start cmd /c ' + execute_path
executable_argv = shlex.split(executable)
pid = find_pid_by_listen_port(9160)
if pid:
    print('kill process id',pid)
    os.kill(int(pid),signal.SIGTERM)
if os.path.exists('d:/deploy'):
    print('Delete d:/deploy')
    shutil.rmtree('d:/deploy')
http_download(download_url, download_file)
os.makedirs(unzip_folder)
print('unzip {0} to {1}'.format(download_file, unzip_folder))
shutil.unpack_archive(download_file, unzip_folder)
print('Execute',execute_path)
subprocess.Popen(executable_argv,shell=True)
    

python download text percent progress

Description

想學一下 Maven download 時候的 text percent progress

Codes

import sys
import math
import urllib.request

def http_download(download_url, download_file):
    with urllib.request.urlopen(download_url) as f:
        with open(download_file,'wb') as target:
            filesize = int(f.getheader('Content-Length'))
            wrotesize = 0
            while True:
                if wrotesize == int(filesize):
                    break
                wrotesize += target.write(f.read(1024))
                download_percent = math.ceil((wrotesize/filesize)*100)
                print('\rDownload {0} to {1} ... {2}%'.format(download_url,download_file,download_percent),end='')

if len(sys.argv) < 3:
    print('Usage: {0} download_url download_file'.format(sys.argv[0]))
else:    
    download_url = sys.argv[1]
    download_file = sys.argv[2]
    http_download(download_url, download_file)

使用方式

c:\workspace_python>python test.py http://ftp.tc.edu.tw/pub/Apache/cassandra/2.0.4/apache-cassandra-2.0.4-bin.tar.gz d:/apache-cassandra-2.0.4-bin.tar.gz

python http download cassandra

Reference

http://www.apache.org/dyn/closer.cgi?path=/cassandra/2.0.4/apache-cassandra-2.0.4-bin.tar.gz
http://docs.python.org/3/library/urllib.request.html#module-urllib.request

Description

用 urllib 下載 cassandra 到本地

Codes

簡單的方式

import urllib.request

with urllib.request.urlopen('http://ftp.tc.edu.tw/pub/Apache/cassandra/2.0.4/apache-cassandra-2.0.4-bin.tar.gz') as f:
    with open('d:/apache-cassandra-2.0.4-bin.tar.gz','wb') as target:
        target.write(f.read())

如果想要看進度可以這樣

import urllib.request

with urllib.request.urlopen('http://ftp.tc.edu.tw/pub/Apache/cassandra/2.0.4/apache-cassandra-2.0.4-bin.tar.gz') as f:
    with open('d:/apache-cassandra-2.0.4-bin.tar.gz','wb') as target:
        filesize = f.getheader('Content-Length')
        wrotesize = 0
        while True:
            if wrotesize == int(filesize):
                break
            wrotesize += target.write(f.read(1024))
            print('download...',wrotesize,'of',filesize)
            

想從公司內的 Maven download 還需要認證

import urllib.request

pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None,'http://mvn.company.site','myid','mypw')
auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
with urllib.request.urlopen('http://mvn.company.site/downloadfile.zip') as f:
    with open('d:/downloadfile.zip','wb') as target:
        target.write(f.read())

後記

還不太清楚 HTTPBasicAuthHandler 的 realm 要怎麼指定正確, 
使用 Maven response 的 realm 也不行.
只好先用 HTTPPasswordMgrWithDefaultRealm 了...

python compress/decompress file

Reference

http://docs.python.org/3/library/shutil.html#module-shutil

Description

把 d:/nginx-1.4.3 壓縮到 d:/ziptarget/test.zip
再把 d:/ziptarget/test.zip 解壓縮到 d:/unziptarget/

Codes (適合 python 3.2 以上)

import shutil

unzipfile_folder = 'd:/unziptarget'
archive_name = 'd:/ziptarget/test'
root_dir = 'd:/nginx-1.4.3'
archive_path = shutil.make_archive(archive_name, 'zip', root_dir)
shutil.unpack_archive(archive_path, unzipfile_folder)

python 的 iterator 與 (神奇的) yield (iterator generator)

Reference

http://docs.python.org/3/tutorial/classes.html#iterators
http://docs.python.org/3/tutorial/classes.html#generators

Iterator

這段程式

for i in range(5):
    print(i)

執行結果為

0
1
2
3
4

可以執行的原因是 range 回傳了一個可以 iterate 的物件,
讓 python 可以呼叫 "next" 取得下一個值.
如果想要自己實作一個能用 for iterate 的物件時,
只需要實作 __iter__ 與 __next__ 這兩個 function,
for 迴圈執行時 python 會自動執行這兩個 function.
我們只要在 __next__ 呼教時維持好物建的狀態即可.
通知 for 迴圈停止的方式是丟出一個 StopIteration 的 error


class NumberIterator:
    def __init__(self, max):
        self.max = max
        self.current = 0
    def __iter__(self):
        print('iter is called. max=',self.max)
        return self
    def __next__(self):
        print('next is called, current=', self.current, ', max=', self.max)
        if ( self.current == self.max ):
            raise StopIteration
        self.current += 1
        return self.current
        
it = NumberIterator(5)
# "for" statement will call iter() of NumberIterator
# so 'iter is called. max=' will be printed
for i in it:
    print(i) #print 1 ~ 5

# there is no "for" statement, so 'iter is called. max=' won't be printed
it = NumberIterator(4)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it)) #StopIteration

執行結果

d:\workspace_python>python test.py
iter is called. max= 5
next is called, current= 0 , max= 5
1
next is called, current= 1 , max= 5
2
next is called, current= 2 , max= 5
3
next is called, current= 3 , max= 5
4
next is called, current= 4 , max= 5
5
next is called, current= 5 , max= 5
next is called, current= 0 , max= 4
1
next is called, current= 1 , max= 4
2
next is called, current= 2 , max= 4
3
next is called, current= 3 , max= 4
4
next is called, current= 4 , max= 4
Traceback (most recent call last):
  File "test.py", line 27, in 
    print(next(it)) #StopIteration
  File "test.py", line 11, in __next__
    raise StopIteration
StopIteration

yield (iterator generator)

神奇的 yield, 這個 statement 是出現在 function 裡面, 
讓程式先回傳, 但 function 內的狀態保持不變, 
等下次程式的 __next__ 被呼叫時, 程式會從 yield 之後的碼繼續執行.
def test_yield():
    i = 0
    print('before the first yield',i)
    yield i
    print('after the first yield',i)
    i += 1
    print('before the second yield',i)
    yield i
    print('after the second yield',i)
    i += 1
    for i in range(3):
        print('before yield in for stmt')
        yield i**2
        print('after yield in for stmt')
    
for i in test_yield():
    print(i)

執行結果
d:\workspace_python>python test.py
before the first yield 0
0
after the first yield 0
before the second yield 1
1
after the second yield 1
before yield in for stmt
0
after yield in for stmt
before yield in for stmt
1
after yield in for stmt
before yield in for stmt
4
after yield in for stmt

python 處理 json

Description

現在很常用 json 當成儲存資料的格式, 用 java 的話需要導入 library.
python 則是內建 json 的 module, 只要操作原生的資料結構就行了. 很方便.

Reference

Codes

>>> import json
>>> m = {'a':1,'b':[1,2,3,4,5,6]}
>>> with open('d:/test.txt','w') as f:
        json.dump(m,f)

        
>>> with open('d:/test.txt') as f:
        f.readline()

        
'{"a": 1, "b": [1, 2, 3, 4, 5, 6]}'
>>> with open('d:/test.txt') as f:
        x = json.load(f)

        
>>> x
{'a': 1, 'b': [1, 2, 3, 4, 5, 6]}
>>> 

File content

{"a": 1, "b": [1, 2, 3, 4, 5, 6]}

python 的 main method

之前看 python 文章好像都沒提到怎麼寫 main method, 似乎這件事情很自然, 不過我卻不知道.
看了 6.1.1. Executing modules as scripts 裡面有寫
"the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:"
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
試著作一次

  1. C:\Python33\say.py
    def say(words):
            print(words)
    
    if __name__ == '__main__':
            import sys
            say(sys.argv[1])
            print(__name__,sys.argv[0])
    
    
  2. Output
    C:\Python33>python.exe say.py hello
    hello
    __main__ say.py

這樣就可以了, 很簡單..

處理正在 iterate 的 dictionary


今天練習 Python 的時候發現 5.6. Looping Techniques 有個提示
"To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy."

照著文件上的程式輸入
>>> words = ['a','b','cc']
>>> for w in words:
    if len(w)>1:
        print('insert',w)
        words.insert(0,w)

執行之後就出現
insert cc
insert cc
insert cc
insert cc
insert cc
insert cc
insert cc
insertTraceback (most recent call last):
  File "<pyshell#208>", line 3, in <module>
    print('insert',w)
  File "C:\Python33\lib\idlelib\PyShell.py", line 1318, in write
    return self.shell.write(s, self.tags)
KeyboardInterrupt

要 Ctrl+C 才能停下來.
這時候檢查一下哪打錯了, 原來我打
for w in words:

但文件上是
for w in words[:]:

修正之後果然就正常了.
原來 words[:] 是 words 的 copy.
試一下
>>> words is words
True
>>> words is words[:]
False
果然沒錯.

在 Java 也是一樣, 如果要改變正在 iterate 的 list 也會有問題
package test;

import java.util.Arrays;
import java.util.List;

public class TestIter {

    public static void main(String[] params) {
        List words = Arrays.asList("a","b","cc");
        for (String w: words) {
            if (w.length() > 1) {
                System.out.println("insert " + w);
                words.add(w);
            }
        }
    }
    
}
會報錯
insert cc
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractList.add(Unknown Source)
    at test.TestIter.main(TestIter.java:13)

要改成
package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestIter {

    public static void main(String[] params) {
        List words = Arrays.asList("a","b","cc");
        List copyWords = new ArrayList(words);
        for (String w: words) {
            if (w.length() > 1) {
                System.out.println("insert " + w);
                copyWords.add(0,w);
            }
        }
        System.out.println(words);
        System.out.println(copyWords);
    }
    
}

寫了 Python 跟 Java 這兩段程式, 感覺有微妙的差異...

巴斯卡三角形 in Python

Source Code

def print_pascal(row_cnt):
    pascal = []
    for row in range(row_cnt):
        cols = []
        for col in range(row+1):
            if row == 0:
                cols.append(1)
            elif col == 0 or col == row:
                cols.append(1)
            else:
                val = pascal[row-1][col-1]+pascal[row-1][col];
                cols.append(val)
        pascal.append(cols)
    for row in pascal:
        for i in range(row_cnt-len(row)):
            print('%5s' %'',end='')
        for col in row:
            print('%5d' %col,end='%5s' %'')
        print()

Usage


>>> print_pascal(6)
                             1     
                        1         1     
                   1         2         1     
              1         3         3         1     
         1         4         6         4         1     
    1         5        10        10         5         1  

Lessons Learned While Benchmarking vLLM with GPU

Recently, I benchmarked vLLM on a GPU to better understand how much throughput can realistically be expected in an LLM serving setup. One ...