Wednesday, September 24, 2014

os.fdopen(), os.open(), built-in open()

Python 令吾混淆的檔案開啟函數
os.open()
os.fdopen()
open() [built-in, 內建的函數]

//===
http://stackoverflow.com/questions/15039528/what-is-the-difference-between-os-open-and-os-fdopen-in-python

""" ...
In short, open() creates new file objects,
os.open() creates OS-level file descriptors, and
os.fdopen() creates a file object out of a file descriptor.
...
Built-in open() takes a file name and returns a new Python file object.
This is what you need in the majority of cases.
... """

--> 一般來說, 直接用內建的 open() 就好了.


[example]
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# fd is file descriptor

fo = os.fdopen(fd, "w+")
fo.write( "I am a pig.\nYou are, too.\n");
# fo is file object


fo2 = open("foo.txt", "wb")
fo2.write( "who are you?\nwho's who?\n");
# fo is file object, too.

http://www.tutorialspoint.com/python/python_files_io.htm

pkg_resources

//=== example __init__.py
try:
 import pkg_resources
 __version__ = pkg_resources.require('modulename')[0].version
except:
 __version__ = 'unknown'

//=== pkg_resources
http://stackoverflow.com/questions/7446187/no-module-named-pkg-resources
"""
pkg_resources appears to be distributed with setuptools
"""

setuptools --> ez_setup.py?

setuptools  on pypi
https://pypi.python.org/pypi/setuptools


//=== No module named pkg_resources
http://ubuntuforums.org/showthread.php?t=2167383

$ cat /etc/lsb-release
$ curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | sudo python
$ sudo apt-get install --reinstall python-pkg-resources
$ sudo apt-get install python-pkg-resources python-setuptools --reinstall


[ref]
http://stackoverflow.com/questions/7446187/no-module-named-pkg-resources
http://kelfubuntu.blogspot.tw/2014/07/python27-ezsetup-pip-virtualenv.html
http://ubuntuforums.org/showthread.php?t=2167383

https://pythonhosted.org/setuptools/pkg_resources.html

Sunday, September 21, 2014

"six" module

python 有個模組(module)名為 "six"

python 2 與 python 3 有些語法(syntax)上的差異
例如
print 'xxxx' --> print('xxxx')

資料型別也有些更動
例如
unicode, basestring, str  --> str

物件模型(object-model) 的差異?

"six" 模組的目標就是希望彌平(smoothing) python2 與 python3 的差異
讓python程式碼能夠同時用在兩個版本上.



//=== https://pypi.python.org/pypi/six
"""
...
Six is a Python 2 and 3 compatibility library.
It provides utility functions for smoothing over the differences between the Python versions
with the goal of writing Python code that is compatible on both Python versions.

...
Six supports every Python version since 2.5.
It is contained in only one Python file, ...

...
Author: Benjamin Peterson

...
Package Index Owner: gutworth
DOAP record: six-1.8.0.xml

...

"""


[ref]
https://pypi.python.org/pypi/six
http://pythonhosted.org/six/