2015年12月23日 星期三

[RR Python] pip install pybluez 結果出現 Fatal error: Python.h: No such file or Directory

在利用pip安裝pybluez時,出現下列錯誤訊息
  In file included from bluez/btmodule.c:20:0:
  bluez/btmodule.h:4:20: fatal error: Python.h: No such file or directory
   #include "Python.h"
compilation terminated.
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for pybluez
Failed to build pybluez
一開始以爲是權限問題(真是壞習慣,不仔細看錯誤訊息往往是欲速則不達),加了sudo後還是沒有用的。接著猜是virtualenv環境路徑没設好(這次錯怪它了)。查了Debian / Ubuntu: Fatal error: Python.h: No such file or Directory 才發現是不但没有python.h,整個python-dev都没裝啦啦啦。

sudo apt-get install python-dev

簡單裝完後再pip pybluez,結果
     #include <bluetooth/bluetooth.h>
                                     ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
 
果然代誌不是像憨人想得那麽簡單呀- libbluetooth-dev没裝

總算
Successfully installed pybluez-0.22




2015年9月10日 星期四

[RR Python] 建立獨立開發環境 virtualenv virtualenvwrapper

python的威力是有許多已經被開發的模組可以使用
讓程式設計者能專注在程式功能與邏輯上

然而寫python程式最怕的就是使用不同的版本的模組,甚至是不同版本的python
virtualenv的介紹有提到:
"
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
 "

virtualenv / virtualenvwrapper (大致上)解決了這個問題

建立環境
mkvirtualenv test1

mkvirtualenv test1 -p /usr/bin/python3.3 

離開環境
deactivate
使用先前建立的環境
workon test1
刪除先前建立的環境
rmvirtualenv test1

 
 
 
 
Szymon Lipiński 有相當簡潔的安裝與使用範例

Virtualenv Tutorial Part 2

sudo pip install virtualenvwrapper

mkdir ~/.virtualenvs


A Primer on virtualenv 也提供了使用virtualenv的建議

 

2015年9月8日 星期二

[RR Python] Difference between built in repr() and str() - 兩者的不同

Official definition:
repr(object)
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.


class str(object='')
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
eval(expression[, globals[, locals]])
The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>
>>> x = 1
>>> print eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.
interesting demo below:
>>> s = "x +1"
>>> s
'x +1'
>>> print s
x +1
>>> str(s)
'x +1'
>>> print str(s)
x +1
>>> repr(s)
"'x +1'"

>>> print repr(s)
'x +1'
>>> x = 1
>>> eval(s)
2
>>> eval(str(s))
2
>>> eval(repr(s))
'x +1'
form Python Essential Reference, 4ed.
The __repr__() and __str__() methods create simple string representations of an object.The __repr__() method normally returns an expression string that can be evaluated to re-create the object.This is also the method responsible for creating the output of values you see when inspecting variables in the interactive interpreter.This method is invoked by the built-in repr() function.

a = [2,3,4,5]      # Create a list
s = repr(a)         # s = '[2, 3, 4, 5]'
b = eval(s)         # Turns s back into a list

Furthermore, Difference between __str__ and __repr__ in Python has extensively explanation of them. In short:

  1. __repr__ goal is to be unambiguous
  2. __str__ goal is to be readable
  3. Implement __repr__ for any class you implement. This should be second nature. Implement __str__ if you think it would be useful to have a string version which errs on the side of more readability in favor of more ambiguity.
  4. if you override __repr__, that's ALSO used for __str__, but not vice versa (Container’s __str__ uses contained objects’ __repr__)




[RR Python] lambda function

a lambda function is a function that takes any number of arguments (including optional arguments)
and returns the value of a single expression. lambda functions can not contain commands, and
they can not contain more than one expression.

there are no parentheses around the argument list, and the return keyword is missing (it is implied, since the entire function can only be one expression).

>>>(lambda x: x*2)(3)
6

an other interesting lambda

Why do lambdas defined in a loop with different values all return the same result?



2015年9月3日 星期四

[RR Python] zip is not zip...(compression)

zip([iterable, ...])
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).
zip() in conjunction with the * operator can be used to unzip a list:


 an example:
alp = ['a','b','c','d','e']
num = range(5)

zan = zip(alp, num)
print type(zan), zan

ua, un = zip(*zan)
print ua
print un

and the result:


<type 'list'> [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)]
('a', 'b', 'c', 'd', 'e')
(0, 1, 2, 3, 4)

another example:


list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
zab = zip(list_a, list_b)

print type(zab), zab

and the result:
<type 'list'> [(3, 2), (9, 4), (17, 8), (15, 10), (19, 30)]

apparently, the shorter one is turncated

[RR Python] enumerate

enumerate(sequence, start=0)
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:


vault = "abcdefg"
print type(enumerate(vault))
print list(enumerate(vault))
for index, x in enumerate(vault):
    print index, x
 result:
<type 'enumerate'>
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]
0 a
1 b
2 c
3 d
4 e
5 f
6 g

[RR Python] else statement after while clause

As a C/C++ programmer, it's comfortable to use "while" to loop until certain expected condition happens in python, until I found that it's possible to have "else" after while loop.

there is good example at stackoverflow

and I tried this

vault = [1,2,3]

print "Start"

while vault:
    x = vault.pop(0)
    if x != None:
        print x
    else:
        print "BREAK"
        break
else:
    print "ELSE"
   
print "END"

and the result is
Start
1
2
3
ELSE
END

if change vault to [1,2,3,None]
vault = [1,2,3, None]

print "Start"

while vault:
    x = vault.pop(0)
    if x != None:
        print x
    else:
        print "BREAK"
        break
else:
    print "ELSE"
   
print "END"
the result is
Start
1
2
3
ELSE
END

The "else" can also apply to "for" loop. In short, if the loop test fails, "else" clause is executed, except exiting loop by "break"

Another useful example covers try-catch-else is at Else Clauses on Loop Statements

2015年8月25日 星期二

[RR Python] Unicode in Python

Get system encoding parameter:
sys.getdefaultencoding()
>>> sys.getdefaultencoding()
'ascii'
 Play around with multibyte characters
>>> msg = '今天天氣真好12345'
>>> msg
'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\xa4\xa9\xe6\xb0\xa3\xe7\x9c\x9f\xe5\xa5\xbd12345'

>>> msgu = u'今天天氣真好12345'
>>> msgu
u'\u4eca\u5929\u5929\u6c23\u771f\u597d12345'
 >>> print msg, msgu
今天天氣真好12345 今天天氣真好12345
check their type
>>> print type(msg), type(msgu)
<type 'str'> <type 'unicode'>
 
the length of msg/msgu is interesting
 >>> print len(msg), len(msgu)
23 11
msg is encoded in "utf-8", to verify it, decode it and compare with msgu, they are identical!
>>> msg.decode('utf-8')
u'\u4eca\u5929\u5929\u6c23\u771f\u597d12345'


reference:
瞭解Unicode¶
Python Tutorial 第一堂(4)Unicode 支援、基本 I/O