welcom ! Handel home

2016年5月18日 星期三

Python OO copy and deepcopy 9x9 Pad by SUDO test code

import copy

class suitem:
    def __init__(self):
        dd = [1,2,3,4,5,6,7,8,9]
        ddx = []
        self.set = ['x']*9*9
#        self.data = copy.deepcopy(dd)*9*9
        for i in range(9):
            for j in range(9):
                ddx.append(copy.deepcopy(dd))
        self.data = ddx

    def showset(self):
        for i in range(9):
            print ">>[",
            for j in range(9):
                print self.set[i*9+j],
            print "]<<"

    def showdata(self):
        for i in range(9):
            print ">>[",
            for j in range(9):
                print self.data[i*9+j],
            print "]<<"
           
if __name__ == '__main__':
    sett = suitem()


    a = copy.copy(sett)
    b = copy.deepcopy(sett)

   
    sett.set[0] ='1'
    print "=== other ==="
    sett.showset()
    print "=== other ==="
    a.showset()
    print "=== other ==="
    b.showset()
    print "=== end   ==="
   

2016年5月15日 星期日

python 2.7 and 3.3 install easy_install , pip

yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel


1
2
3
4
5
6
7
8
9
10
11
12
13
# Python 2.7.6:
tar xf Python-2.7.6.tar.xz
cd Python-2.7.6
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall

# Python 3.3.5:
tar xf Python-3.3.5.tar.xz
cd Python-3.3.5
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall


# Then install it for Python 2.7 and/or Python 3.3:
python2.7 ez_setup.py
python3.3 ez_setup.py

# Now install pip using the newly installed setuptools:
easy_install-2.7 pip
easy_install-3.3 pip

# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]





2016年5月11日 星期三

python read the direct [dir ] [file] list

[Python] 取得路徑下檔案
'ss = os.listdir(" ")      
'if  os.path.isfile(ss[0]) :
'if  os.path.isdir(ss[0]):

如何利用python取得特定路徑下的檔案名稱呢? 

其實說起來也相當簡單,os module裡已經定義好了。

先從os.listdir本身會回傳該資料夾下的所有檔案名稱,以list回傳。

再用一個 for 迴圈遍訪每個檔名,對其用os.path.isfile()判斷即可(若要取資料夾使用os.path.isdir())。

以下為範例程式碼。


import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
        print f
上面是個簡潔有力的寫法,他的效果等義於下列程式碼:

import os
files = []

for f in os.listdir('.'):
        if os.path.isfile(f):
                files.append(f)
for f in files:
        print f



2016年5月10日 星期二

pip auto update the package tool Demo


PIP command example : 操作命令

  • pip list # 看目前系統有安裝哪些套件
  • pip search mysql # 搜尋相關套件
  • pip install package # 安裝套件
  • pip uninstall package # 移除套件
  • pip show --files package # 秀套件檔案列表
  • pip list --outdated # 列出過期套件
  • pip install --upgrade package # 升級

>> save next code to pipupv27.py
>> python2 pipupv27.py
then will auto scan the pip upgrade package list and  type y/a/n to select the function


#====================================================
import time
import sys
import os

os.system("pip2.7 list --outdated > chklist.txt")
f = open("chklist.txt",'r')
ss = f.read()
f.close()
kss = ss.split("\n")
#print ss

for i in kss:
    print (i)

kk='n'
kk2='n'
kk = raw_input("\nare you want to upgrate(y:1by1/a:all/n) : ")
if kk == 'n':
    print "\nby by ..."
    exit()

if kk == 'a':
        for i in kss:
                if i.split(" ")[0] != "numpy":
                    os.system("pip2.7 install --upgrade "+i.split(" ")[0])
else:
        for i in kss:
                ss2 = i.split(" ")[0]
                print (ss2)
                kk2 = raw_input("\n update it (y n):")
                if kk2 == 'y':
                    if i.split(" ")[0] != "numpy":
                        os.system("pip2.7 install --upgrade "+i.split(" ")[0])
                else:
                    print ("\npass to next")

#========================================================


2016年5月9日 星期一

python use dict function run ( by switch case example code )

# coding=utf-8

def key1(ss):
    print ("\n run %s ok !" % ss)
    pass
         
def key2(ss):
    print ("\n run %s ok !" % ss)
    pass
           
def key3(ss):
    print ("\n run %s ok !" % ss)
    pass
 
def key4(ss):
    print ("\n run %s ok !" % ss)
    pass

caseloop = {
    "k1":key1,
    "k2":key2,
    "k3":key3,
    "k4":key4
 }    
     
if __name__ == '__main__':
    while 1:
        kk = input("\n type key:")
        caseloop[kk](kk)

2016年5月8日 星期日

python Functin set array call Example

# Function Set call by index    
def aa():
  print ("is aa run !\n")
 
def bb():
  print ("is bb run !\n")  

def cc():
  print ("is cc run !\n")

def dd():
  print ("is dd run !\n")

workp = {0:aa,1:bb,2:cc,3:dd}  

if __name__ == '__main__':
  print ("hello dir call test ! \n ================== \n")
  aa(),bb(),cc(),dd()
  print ("hello set call test ! \n ================== \n")
  workp[0]()                                              
  workp[1]()
  workp[2]()
  workp[3]()


run Ex:
hello dir call test !
 ==================
is aa run !
is bb run !
is cc run !
is dd run !
hello set call test !
 ==================
is aa run !
is bb run !
is cc run !
is dd run !

================================================
EXample 2
def plus_1(x):
    return x + 1

def minus_1(x):
    return x - 1

func_map = {'+' : plus_1, '-' : minus_1}

print (func_map['+'](3))  # returns plus_1(3) ==> 4
print (func_map['-'](3))  # returns minus_1(3) ==> 2


2016年5月4日 星期三

python print format demo

>>> print (" %3d %3d %4x" %(9,9,9))
   9   9    9
>>> print (" %3d %3d %04x" %(9,9,9))
   9   9 0009
>>> print (" %3d %3d %04x" %(9,9,12))
   9   9 000c
>>> print (" %03d %03d %04x" %(9,9,12))
 009 009 000c
>>> print (" %03d %05d %04x" %(9,9,12))
 009 00009 000c
>>> print (" %03d %05d %04x %s" %(9,9,12,"hello"))
 009 00009 000c hello
>>> q = 459
>>> p = 0.098
>>> print(q, p, p * q)
459 0.098 44.982
>>> print(q, p, p * q, sep=",")
459,0.098,44.982
>>> print(q, p, p * q, sep=" :-) ")
459 :-) 0.098 :-) 44.982
>>> 
General way of working of the string modulo operator


General way of working of the string modulo operator, format string 
The format string contains placeholders. There are two of those in our example: "%5d" and "%8.2f". 

>>> print("%10.3e"% (356.08977))
 3.561e+02
>>> print("%10.3E"% (356.08977))
 3.561E+02
>>> print("%10o"% (25))
        31
>>> print("%10.3o"% (25))
       031
>>> print("%10.5o"% (25))
     00031
>>> print("%5x"% (47))
   2f
>>> print("%5.4x"% (47))
 002f
>>> print("%5.4X"% (47))
 002F
>>> print("Only one percentage sign: %% " % ())
Only one percentage sign: % 
>>> 
>>> print("%#5X"% (47))
 0X2F
>>> print("%5X"% (47))
   2F
>>> print("%#5.4X"% (47))
0X002F
>>> print("%#5o"% (25))
 0o31
>>> print("%+d"% (42))
+42
>>> print("% d"% (42))
 42
>>> print("%+2d"% (42))
+42
>>> print("% 2d"% (42))
 42
>>> print("%2d"% (42))
42
>>> s = "Price: $ %8.2f"% (356.08977)
>>> print(s)
Price: $   356.09
>>>

General way of working of the format method with positional parameters

Examples of positional parameters:
>>> "First argument: {0}, second one: {1}".format(47,11) 
'First argument: 47, second one: 11'
>>> "Second argument: {1}, first one: {0}".format(47,11) 
'Second argument: 11, first one: 47'
>>> "Second argument: {1:3d}, first one: {0:7.2f}".format(47.42,11) 
'Second argument:  11, first one:   47.42'
>>> "First argument: {}, second one: {}".format(47,11) 
'First argument: 47, second one: 11'
>>> # arguments can be used more than once:
... 
>>> "various precions: {0:6.2f} or {0:6.3f}".format(1.4148) 
'various precions:   1.41 or  1.415'
>>> 
In the following example we demonstrate how keyword parameters can be used with the format method:
>>> "Art: {a:5d},  Price: {p:8.2f}".format(a=453, p=59.058)
'Art:   453,  Price:    59.06'
>>> 
General way of working of the format method with keyword parameters  It's possible to left or right justify data with the format method. To this end, we can precede the formatting with a "<" (left justify) or ">" (right justify). We demonstrate this with the following examples: 
>>> "{0:<20s 6.99="" amp="" eggs:="" f="" format="" pam="">>> "{0:>20s} {1:6.2f}".format('Spam & Eggs:', 6.99)
'        Spam & Eggs:   6.99'
>>> "{0:>20s} {1:6.2f}".format('Spam & Ham:', 7.99)
'         Spam & Ham:   7.99'
>>> "{0:<20s 7.99="" amp="" f="" format="" ham:="" pam="">>> "{0:<20 7.99="" amp="" f="" format="" ham:="" pam="">>> "{0:>20} {1:6.2f}".format('Spam & Ham:', 7.99)
'         Spam & Ham:   7.99'
>>> 
OptionMeaning
'<'The field will be left-aligned within the available space. This is usually the default for strings.
'>'The field will be right-aligned within the available space. This is the default for numbers.
'0'If the width field is preceded by a zero ('0') character, sign-aware zero-padding for numeric types will be enabled.
>>> x = 378
>>> print("The value is {:06d}".format(x))
The value is 000378
>>> x = -378
>>> print("The value is {:06d}".format(x))
The value is -00378
','This option signals the use of a comma for a thousands separator.
>>> print("The value is {:,}".format(x))
The value is 78,962,324,245
>>> print("The value is {0:6,d}".format(x))
The value is 5,897,653,423
>>> x = 5897653423.89676
>>> print("The value is {0:12,.3f}".format(x))
The value is 5,897,653,423.897
'='Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form "+000000120". This alignment option is only valid for numeric types.
'^'Forces the field to be centered within the available space.
Unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.
Additionally, we can modify the formatting with the sign option, which is only valid for number types:
OptionMeaning
'+'indicates that a sign should be used for both positive as well as negative numbers.
'-'indicates that a sign should be used only for negative numbers, which is the default behavior.
spaceindicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

Using dictionaries in "format"

We have seen in the previous chapters that we have two ways to access the values to be formatted:
  • Using the position or the index:
    >>> print("The capital of {0:s} is {1:s}".format("Ontario","Toronto"))
    The capital of Ontario is Toronto
    >>> 
    
    Just to mention it once more: We could have used empty curly braces in the previous example!
  • Using keyword parameters:
    >>> print("The capital of {province} is {capital}".format(province="Ontario",capital="Toronto"))
    The capital of Ontario is Toronto
    >>>
    
The second case can be expressed with a dictionary as well, as we can see in the following code:
>>> print("The capital of {province} is {capital}".format(**k))
The capital of Ontario is Toronto
>>> 
Let's look at the following Python program:
capital_country = {"United States" : "Washington", 
                   "US" : "Washington", 
                   "Canada" : "Ottawa",
                   "Germany": "Berlin",
                   "France" : "Paris",
                   "England" : "London",
                   "UK" : "London",
                   "Switzerland" : "Bern",
                   "Austria" : "Vienna",
                   "Netherlands" : "Amsterdam"}

print("Countries and their capitals:")
for c in capital_country:
    print("{country}: {capital}".format(country=c, capital=capital_country[c]))
If we start this program, we get the following output:
$ python3 country_capitals.py 
Countries and their capitals:
United States: Washington
Canada: Ottawa
Austria: Vienna
Netherlands: Amsterdam
Germany: Berlin
UK: London
Switzerland: Bern
England: London
US: Washington
France: Paris
We can rewrite the previous example by using the dictionary directly. The output will be the same:
capital_country = {"United States" : "Washington", 
                   "US" : "Washington", 
                   "Canada" : "Ottawa",
                   "Germany": "Berlin",
                   "France" : "Paris",
                   "England" : "London",
                   "UK" : "London",
                   "Switzerland" : "Bern",
                   "Austria" : "Vienna",
                   "Netherlands" : "Amsterdam"}

print("Countries and their capitals:")
for c in capital_country:
    format_string = c + ": {" + c + "}" 
    print(format_string.format(**capital_country))

Using Local Variable Names in "format"

"locals" is a function, which returns a dictionary with the current scope's local variables, i.e- the local variable names are the keys of this dictionary and the corresponding values are the values of these variables:
>>> a = 42
>>> b = 47
>>> def f(): return 42
... 
>>> locals()
{'a': 42, 'b': 47, 'f': , '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__': None}
>>> 
The dictionary returned by locals() can be used as a parameter of the string format method. This way we can use all the local variable names inside of a format string.  Continuing with the previous example, we can create the following output, in which we use the local variables a, b and f:
>>> print("a={a}, b={b} and f={f}".format(**locals()))
a=42, b=47 and f=

Other string methods for Formatting

The string class contains further methods, which can be used for formatting purposes as well: ljust, rjust, center and zfill  Let S be a string, the 4 methods are defined like this:
  • center(...):
    S.center(width[, fillchar]) -> str
    
    Return S centred in a string of length width. Padding is done using the specified fill character. The default value is a space.  Examples:
    >>> s = "Python"
    >>> s.center(10)
    '  Python  '
    >>> s.center(10,"*")
    '**Python**'
    
  • ljust(...):
     S.ljust(width[, fillchar]) -> str 
    
    Return S left-justified in a string of length "width". Padding is done using the specified fill character. If none is given, a space will be used as default.  Examples:
    >>> s = "Training"
    >>> s.ljust(12)
    'Training    '
    >>> s.ljust(12,":")
    'Training::::'
    >>> 
    
  • rjust(...):
    S.rjust(width[, fillchar]) -> str
    
    Return S right-justified in a string of length width. Padding is done using the specified fill character. The default value is again a space.  Examples:
    >>> s = "Programming"
    >>> s.rjust(15)
    '    Programming'
    >>> s.rjust(15, "~")
    '~~~~Programming'
    >>> 
    
  • zfill(...):
     
    S.zfill(width) -> str
    
    Pad a string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. This method can be easily emulated with rjust.  Examples:
    >>> account_number = "43447879"
    >>> account_number.zfill(12)
    '000043447879'
    >>> # can be emulated with rjust:
    ... 
    >>> account_number.rjust(12,"0")
    '000043447879'
    >>> 
    

Python 應用實例


許多軟體及網站程式已經使用 Python 來開發,下列是一些例子:
  • 教學環境: 美國麻省理工學院 (MIT EECS) 新生程式語言入門,選用 Python 為預設教材。
  • 行動裝置開發環境: OLPCNokia S60Moblin 都提供 Python 應用程式的開發環境。
  • 入口網站服務: Google, YouTube, Yahoo! 網站的關鍵服務以 Python 語言開發。
  • 動畫軟體: MayaBlender 語言擴充介面支援 Python 語言。
  • 圖形介面及動畫遊戲: wxPythonPyGame 是協助創作的好工具。
  • 郵遞論壇: mailman 程式以 Python 語言寫成。
  • 網頁應用伺服與開發框架: Google App EnginelaunchpadZopeDjangoTurboGearsPylons 是主要的範例。
  • 安裝程式: Red Hat Linux 開機安裝程式及 Gentoo 套件管理。
  • 檔案點對點分享工具: BitTorrent 工具程式以 Python 語言開發。
  • 科學運算: BiopythonSciPyPyPVM

Python command demo Array , function call

# /pycode  code demo 1
__author__ ="Handel liao 20160505"
#simx1

#=====================================
print ("=====string and number  =====")
a =33
b = "abc"
c =12.1

print ("hello")
print (a)
print (b)
print (c)
print (a+c)

#=====================================
print ("===== python logic shift ===")
print (a<<1 p="">print (a/4)
print (a>>1)
print (a%4)


#=====================================
print ("====Array show =============")

a=['apple','welcom','car','table','telephone','tv','pc','nb']

for x in a:
  print (x,a.index(x))

print ("len = ",len(a))
print ("min = ",min(a))
print ("max = ",max(a))

print ("befert sort => ",a)
a.sort()
print ("after  sort => ",a)

# /pycode  code demo 2
__author__ ="Handel liao 20160505"
#simx2 by def test


#=====================================
print ("====function call ===================")
def fun1():
  print ("this is fun1 !")

def fun2(num):
  print ("this is fun2 = " + str(num))

def fun3(num1,num2):
  num3 = num1+num2
  print ("this is fun3 by "+str(num1)+"+"+str(num2)+"="+str(num3))
  return num3

#=====================================
print ("=============================")

fun1()
fun2(100)
yy = fun3(10,22)
print ("add fun => ",yy)

Raspberry Install python Package TOOL

#download ez_setup.py


$python3 ez_setup.py

$easy_install pip

#=====================================
#yolk the python package check TOOL
$easy_install yolk

   $ yolk -l   #list package
   $ yolk -a   #list active package
   $ yolk -U   #list need update package
 
#=====================================
#install python3 pyserial

$wget 
  1. $tar -xzf pyserial-3.0.1.tar.gz
  2. $cd pyserial-3.0.1
  3. $sudo python setup.py install

#=====================================
# install the minicom tool  by usrt com port test link

$sudo apt-get install minicom
$minicom -b 115200 -o -D /dev/ttyAMA0