sys.path.append()는 파이썬에서 모듈이나 파이썬 파일 읽을 때, 유용한 명령어이다. 자바의 classpath와 비슷하게 python path을 추가할 수 있다.



$ python

>>> import sys

>>> sys.path

['', '/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']

>>> sys.path.append("/mydev/")

>>> sys.path

['', '/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages', '/mydev/']



'python' 카테고리의 다른 글

pip 간단 설명서  (0) 2016.01.25
[python] python 2.7.9에 해당되는 pip 설치하기  (0) 2016.01.22
[python] sys모듈의 sys.path 추가하기  (0) 2016.01.22
[python] zookeeper client - kazoo 예제  (0) 2016.01.05
[python] json 처리  (0) 2016.01.05
pythonic 이란.  (0) 2015.08.25
Posted by 김용환 '김용환'



python kazoo 클라이언트로 zookeeper 값 얻어오기.


http://kazoo.readthedocs.org/en/latest/basic_usage.html



#!/usr/bin/python


from kazoo.client import KazooClient

from kazoo.exceptions import NoNodeError

from kazoo.exceptions import NodeExistsError


import logging

import json

import sys


logging.basicConfig()


zk_key="/com/google/kazoo"


zk = KazooClient(hosts='a.google.com:2181,b.google.com:2181,c.google.com:2181')


zk.start()


try :

print zk.exists(zk_location_redis_key)

data, stat = zk.get(zk_key)

print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))

decoded = json.loads(data)

hostAndport = decoded['slaves'][0]

print hostAndport

except (ValueError, KeyError, TypeError):

print "JSON format error"

except (NoNodeError, NodeExistsError):

print "zk error"


zk.stop()





Posted by 김용환 '김용환'

[python] json 처리

python 2016.01.05 14:14


python에서 json 처리 예제. 




>>> import json


>>> json_string = '{"master":"1.1.1.1:1111", "slave":["2.2.2.2:2222", "3.3.3.3:3333"]}'


>>> decoded = json.loads(json_string)


>>> print json.dumps(decoded, indent=2)

{

  "slave": [

    "2.2.2.2:2222",

    "3.3.3.3:3333"

  ],

  "master": "1.1.1.1:1111"

}


>>> print json.dumps(decoded, indent=2, sort_keys=True)

{

  "master": "1.1.1.1:1111",

  "slave": [

    "2.2.2.2:2222",

    "3.3.3.3:3333"

  ]

}



>>> print decoded['master']

1.1.1.1:1111


>>> print decoded['slave']

[u'2.2.2.2:2222', u'3.3.3.3:3333']


>>> print decoded['slave'][0]

2.2.2.2:2222


>>> print decoded['slave'][1]

3.3.3.3:3333

Posted by 김용환 '김용환'

pythonic 이란.

python 2015.08.25 20:35



아. 처음 들어본 단어 pythonic은 파이썬 개발 방식(또는 파이썬 커뮤니티가 수긍하는 개발 방식)을 따르는 것을 의미하는 것 같다.


http://blog.startifact.com/posts/older/what-is-pythonic.html

http://stackoverflow.com/questions/25011078/what-does-pythonic-mean



Exploting the features of the Python language to produce code that is clear, concise and maintainable.

Pythonic means code that doesn't just get the syntax right but that follows the conventions of the Python community and uses the language in the way it is intended to be used.

This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of unpythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or java. Loops are particularly common examples of this.

For example in Java I might use

for i in (i; i < items.length ; i++)
 {
  n = items[i];
 ... now do something
 }

In Python we can try and replicate this using while loops but it would be cleaner to use

enter code here
for i in items:
  i.perform_action()

Or, even a generator expression

(i.some_attribute for i in items)

So essentially when someone says something is unpythonic, they are saying that the code could be re-written in a way that is a better fit for pythons coding style.

Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for "import this" is decidedly, and by design, unpythonic! Take a look at it for an example of what know to do.



Posted by 김용환 '김용환'

Pandas 라이브러를 하루 정도 이용해보고 나서 얻은 좋은 정보들이다.


pandas의 slice, dataframe 공부가 쉽지 않다. pandas.pydata.org 의 데이터만으로 해결할 수 있는 문제는 stack overflow를 참조해야 한다. 


https://wikidocs.net/1910


http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html

http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series

http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe

http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.query.html

http://cinema4dr12.tistory.com/entry/Statistics-Descriptive-Statistics-Sample-Statistics

http://stackoverflow.com/questions/26414913/normalize-rows-of-pandas-data-frame

http://stackoverflow.com/questions/18792918/pandas-combining-2-data-frames-join-on-a-common-column







Posted by 김용환 '김용환'



ipython notebook에서 pandas 사용할 때 다음 에러가 발생했다.


numpy.dtype has the wrong size, try recompiling

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "/Library/Python/2.7/site-packages/pandas/__init__.py", line 6, in <module>

    from . import hashtable, tslib, lib

  File "numpy.pxd", line 157, in init pandas.hashtable (pandas/hashtable.c:22331)

ValueError: numpy.dtype has the wrong size, try recompiling




버전은 최신이라서 문제가 없는 것 같았다.


$ pip show pandas

---

Name: pandas

Version: 0.16.2

Location: /Library/Python/2.7/site-packages

Requires: numpy, python-dateutil, pytz

$ pip show numpy

---

Name: numpy

Version: 1.9.2

Location: /Library/Python/2.7/site-packages/numpy-1.9.2-py2.7-macosx-10.9-intel.egg

Requires:


pip uninstall 해도 진전이 없다가 다음 싸이트에서 보고, 따라하니(easy_install 설치) pandas를 잘 사용할 수 있었다.


https://github.com/pydata/pandas/issues/7517

@phani-vadrevu Following your instructions, I can import pandas finally.
1. updated numpy to 1.9.0 using "sudo easy_install -U numpy" (while "sudo pip install -U numpy" did nothing but keep the old version)
2. checked whether numpy was updated to the latest version
3. updated pandas to the latest version using easy_install
4. checked whether importing pandas works.
5. done.








Posted by 김용환 '김용환'


ipython notebook (http://ipython.org/notebook.html) 설치하려면,


설치 문서(http://ipython.org/install.html)처럼 하지 말고. 아래와 같이 하면 된다. 

(http://ipython.org/ipython-doc/2/install/install.html)


$ sudo pip install "ipython[all]"




그 다음, 예제를 테스트하기 위해서 아래 소스를 다운 받는다.


https://github.com/ipython/ipython




그리고, 소스 받은 디렉토리에서 다음 커맨드를 실행한다.

$ ipython notebook



예제를 찾아 실행한다.





* lib 설치

numpy, scipy,matplotlib은 같이 설치된다.

그러나 pandas는 같이 설치 안되서 같이 설치한다.


$ pip install pandas 


Posted by 김용환 '김용환'

 

 

#!/usr/bin/python

fname = "a.txt”
nfname = "b.txt"

f = open(fname)  
for line1 in f:     
    print 'line : %s ' %line1
    nnif = open(nfname)
    for line2 in nnif:
        if line1 in line2 : 
            print 'found string in file %s' %line2
            break

Posted by 김용환 '김용환'
 
Erlang 언어를 보면서 참 재미없다고 생각했다.. 당시 얼마나 나는 java api에 길들여져 있었을까..
그리고, java, c 외엔 관심도 없었는데..

내가 사용해본 언어를 보면.. 그리 많지 않다.

java > perl > javascript > c > c++ , sh(csh, bash) > python >> cobol 정도..

개인적으로 go 언어를 볼까 싶다... language에 대한 깊이를 슬슬 올려야지~

홈페이지
http://golang.org/

tutorial 
http://golang.org/doc/go_tutorial.html

Go와 Brand X 비교
http://www.cowlark.com/2009-11-15-go/

한국 분이 간단히 발표한 자료
http://rein.kr/blog/archives/2288
Posted by 김용환 '김용환'

 

 

Python development with Eclipse and Ant

http://www-128.ibm.com/developerworks/opensource/library/os-ecant/

 

RPS Technologies - Python Ant tasks

http://www.rpstechnologies.net/PyAntTasks.html

 

------------------------------------------------------------------

 

 

Python development using the Eclipse IDE and Apache Ant build tool

 

Using Eclipse for Python development

Overview of Eclipse

Eclipse is a Java technology integrated development environment that was developed and open sourced by IBM. It is the basis for IBM's commercial WebSphere Application Development environment, and various other tools. Eclipse has an extremely active community of developers who develop Eclipse itself and the large number of plug-ins available for it. See the Resources section for links to the Eclipse and Eclipse plug-ins Web sites. Although traditionally a tool for Java development, several plug-ins exist for developing with other languages within Eclipse, including C/C++, Python, and Perl.

Within Eclipse, source code is organized into projects. Projects may be loaded, unloaded, and imported. The Eclipse user interface is structured into views and editors. Examples of views and editors include the source code outline view, Java source editor, Python source editor, and filesystem navigator view. One of the key metaphors within the Eclipse user interface is the perspective. Perspectives are an organization of views that would typically be used together when carrying out some type of activity. The perspectives that are standard with Eclipse are: Debug, Java Browsing, Java, Java Type Hierarchy, Plug-in Development, CVS Repository Exploring, Resource, and the Install/Update perspective. A separate Python perspective does not currently exist. When doing Python development, I typically use the Resource perspective and Debug perspective.

Installing PyDev

To get started, download and install Eclipse from the Eclipse Web site (see link in Resources section), following the installation instructions appropriate for your platform.

The Eclipse update facility makes it easy to install the PyDev plug-in. From within Eclipse, select Help > Software Updates > Update Manager to start the Install/Update perspective. In the Feature Updates view at the bottom left, add the PyDev plug-in update site as a new Site Bookmark under the folder "Sites to Visit". The Eclipse update site URL for PyDev is http://pydev.sf.net/updates/. "PyDev" should now be displayed as a feature in the Feature Updates editor. In the Feature Updates editor, expand PyDev > Other, and select the PyDev feature which is displayed (should be at least 0.4.1). Then select "Install Now" to install the feature. Eclipse will download the PyDev plug-in and install it into Eclipse.

Importing the sample project

To access the sample code used within this project, download the zip file (see Resources section), expand the zip file into your filesystem, and then import the contained project into Eclipse. To import the project, switch into the Resource perspective, select File > Import, select "Existing Project into Workspace", and select the location where you expanded the zip file. The feedParserTest project should now appear in the Navigator view.

For the sample project, I've included the Feed Parser universal feed parser library, which is distributed under the Python open source license. See the Resources section for a link to the Feed Parser project Web site.

Posted by 김용환 '김용환'