C 에서 python을 불러서 사용하는 방법인데, 아직 복잡한 예제는 발견하지 못했다.

테스트한 플랫폼은
Fedora Core 6
Python 2.4.3 이다.

# cat py.c
#include <Python.h>

int main()
{
        Py_Initialize();
        PyRun_SimpleString("print 'Hello Python C/API'");
        Py_Finalize();
        return 0;
}

[링크 : http://koichitamura.blogspot.com/2008/06/this-is-small-python-capi-tutorial.html]

# gcc py.c -I/usr/include/python2.4 -lpython2.4
# a.out
Hello Python C/API


이렇게 메시지가 출력된다.

아마 2.4와 2.6이 혼합되어 설치되어있고, 2.6이 정상설치가 되지 않은듯 싶다.
옵션에 따라서 이러한 오류가 발생했다.


웃긴건, 헤더는 2.6으로 링킹은 2.4로 해도 이상이 없다는 점이다.
(뭥미?)
Posted by 구차니
x86 계열에서 메모리 팍팍 쓰면서 속도를 향상시켜준다는,
마법의(!?) JIT(Just In Time) compiler 이다.
결론은.. x86이 아니면 안되는군 ㅠ.ㅠ

 What you can do with it
     

In short: run your existing Python software much faster, with no change in your source.

Think of Psyco as a kind of just-in-time (JIT) compiler, a little bit like what exists for other languages, that emit machine code on the fly instead of interpreting your Python program step by step. The difference with the traditional approach to JIT compilers is that Psyco writes several version of the same blocks (a block is a bit of a function), which are optimized by being specialized to some kinds of variables (a "kind" can mean a type, but it is more general). The result is that your unmodified Python programs run faster.

Benefits

    2x to 100x speed-ups, typically 4x, with an unmodified Python interpreter and unmodified source code, just a dynamically loadable C extension module.

Drawbacks

    Psyco currently uses a lot of memory. It only runs on Intel 386-compatible processors (under any OS) right now. There are some subtle semantic differences (i.e. bugs) with the way Python works; they should not be apparent in most programs.

[링크 : http://psyco.sourceforge.net/]

[링크 : http://www.ibm.com/developerworks/kr/library/l-psyco.html]
Posted by 구차니

검색을 해보니 wxPython에 자체적으로 flash를 재생할수 있는 기능이 있다고 한다.
[링크 : http://www.daniweb.com/forums/thread64949.html#]


머, 중요한건 일단
1. wxPython은 Python이 있어야 작동을 하고.
2. wxPython은 wxWidgets 의 wrapper 라는 것 (그러니까 wxWidget도 설치 되어있어야 하겠지?)
    음.. 근데 버전에 따라 다른가? 이제는 glib 와 gtk+ 가 필요하다고 하는군!

[링크 : http://www.wxpython.org/what.php]
[링크 : http://www.joinc.co.kr/modules/moniwiki/wiki.php/article/wxpython_프로그래밍]

Linux/Unix/Etc.
  • The first thing you'll need are the glib and gtk+ libraries. Before you run off and download the sources check your system, you probably already have it. Most distributions of Linux come with it and you'll start seeing it on many other systems too now that Sun and others have chosen GNOME as the desktop of choice. If you don't have glib and gtk+ already, you can get the sources here. Build and install them following the directions included.
  • In order to use the wxGLCanvas you'll need to have either OpenGL or the Mesa3D library on your system. wxPython's wx.glcanvas.GLCanvas only provides the GL Context and a wx.Window to put it in, so you will also need the PyOpenGL Python extension modules as well, if you want to use OpenGL.

    If you are building wxPython yourself and don't care to use OpenGL/Mesa then you can easily skip building it and can ignore this step. See the build instructions for details.

[링크 : http://wxpython.org/download.php]



아무튼 3색의 사각형 로고가 wx 계열인듯 하다.
Posted by 구차니
Python 2.6 이라고 명시한 이유는, 3.0 에서는 없어지거나 이름이 바뀌었기 때문이다.

htmllib
Deprecated since version 2.6: The htmllib module has been removed in Python 3.0.
urlib
The urllib module has been split into parts and renamed in Python 3.0 to urllib.request, urllib.parse, and urllib.error.
httplib
The httplib module has been renamed to http.client in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

아무튼, 파이썬 프로젝트 분석시에 버전 정보가 애매모호하면 htmllib가 존재하면 2.6.x 대라고 이해하면 되겠다.(?)

[링크 : http://docs.python.org/contents.html]
    [링크 : http://docs.python.org/library/htmllib.html]
    [링크 : http://docs.python.org/library/urllib.html]
    [링크 : http://docs.python.org/library/httplib.html]
Posted by 구차니
문자열은 "" 로
리스트는 []로
사전은 {}로 나타낸다.

문자열은 * 연산을 오버로딩 하고 있고 + 연산으로 여러가지 문장을 합쳐서 출력할수 있다.
(마이너스와 나누기는 안되는듯)

리스트는 배열과 비슷하게 사용이 가능하고
list[0:0] = [value] 이런식으로 리스트의 특정 위치에 값을 추가 할수 있다.
list[0:1] 하면 0번째 에서 1번째 미만의 값을 출력한다.(머 실질적으로 배열에서 0번째 값을 출력하는 셈이다)
리스트를 선언하려면
var = []
라고 선언하고 추후에 추가해주면된다.

사전도 리스트와 비슷하지만
문자열로 값을 찾아야 하고, 값과 숫자를 묶어서 입력해야 한다.
사전을 선언하려면
var = {}
라고 선언하고 추후에 추가해주면된다.

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


[링크 : http://docs.python.org/tutorial/datastructures.html]

>>> tel = {'jack':4098, 'sape':4139}
>>> tel
{'sape': 4139, 'jack': 4098}
>>> tel['sape']
4139

>>> tel[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0

>>> tel[4139]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4139

>>> tel[sape]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sape' is not defined

어떻게 보면 enum 형 같기도 하고.. associative memory 라는데 어디에 쓰는건지 모르겠다. ㅠ.ㅠ
Posted by 구차니
혹시나 해서 exit, bye(무슨 ftp인가 ㅋㅋ) 별걸 다 쳐봤는데 (quit도 아니다!)

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit

보다시피 exit()를 입력하거나, ctrl-D를 하면 종료한다.
음.. EOF니까 windows 버전은 ctrl-z 되려나?



2010.02.26 추가
python 2.4의 경우 무조건 Ctrl-D만 적용된다.


2010.03.21 추가
>>> exit
Use exit() or Ctrl-Z plus Return to exit
Windows 용은 Ctrl-Z 이다.
Posted by 구차니
솔찍히 이해를 못한 부분인데, 간단한 함수를 만드는 것 같다.
함수 포인터 같기도 한데 LISP에서 따왔다고도 하는데 먼소리인지 안드로메다로.

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda".

>>> def f (x): return x**2
... 
>>> print f(8)
64
>>> 
>>> g = lambda x: x**2
>>> 
>>> print g(8)
64

As you can see, f() and g() do exactly the same and can be used in the same ways. Note that the lambda definition does not include a "return" statement -- it always contains an expression which is returned. Also note that you can put a lambda definition anywhere a function is expected, and you don't have to assign it to a variable at all. 


[링크 : http://www.secnetix.de/olli/Python/lambda_functions.hawk]


4.7.5. Lambda Forms

By popular demand, a few features commonly found in functional programming languages like Lisp have been added to Python. With the lambda keyword, small anonymous functions can be created. Here’s a function that returns the sum of its two arguments: lambda a, b: a+b. Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:

>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

[링크 : http://docs.python.org/tutorial/controlflow.html]

아무튼,
>>> f
<function <lambda> at 0xb754da3c>

위의 예제 실행후 f만 입력하면 위와 같이 fuction <lambda> 라는 말이 나온다.
일종의 간단한 return이 필요없는 함수 - c에서 inline 함수? - 가 되는 것처럼 보인다.
Posted by 구차니
파이썬은 "(쌍따옴표) 나 '(홀따옴표) 로 문자열을 변수에 저장한다.
특이하게도 """(쌍따옴표 3개) 라는 녀석이 있는데, 굳이 비유를 하자면 HTML의 <pre> 태그와 비슷한 느낌이다.

아래의 예를 보면, " 로 한녀석은 엔터치면 에러가 발생하는데 비해
>>> hello = "test
  File "<stdin>", line 1
    hello = "test
                ^
SyntaxError: EOL while scanning string literal

"""(쌍따옴표 3개)를 사용한 녀석은 아래와 같이 """ 가 나올때 까지 계속 입력을 받고, 자동으로 \n를 붙여준다.
>>> hello = """test
... asdf
... """

>>> hello
'test\nasdf\n'

>>> print hello
test
asdf

>>>

테스트 삼아 "와 '를 혼용해서 하는데 "와 "를 동시에 쓰면 문법에러가 발생한다.
이런 경우에는 \" 를 이용하여 구분을 해주어야 한다.
>>> ""test" ing"
  File "<stdin>", line 1
    ""test" ing"
         ^
SyntaxError: invalid syntax

>>> '"test" ing'
'"test" ing'

>>> "'test' ing"
"'test' ing"

Posted by 구차니
클래스 내부에 __init__ 메소드와 __del__ 메소드는
객체에서 말하는 constructor와 descructor를 의미한다(고 한다.)

파이썬은 객체지향도 지원해서 연산자 오버로딩도 지원하나보다.
__add__ __cmp__ 메소드를 통해 덧셈과 비교를 오버로딩한다.

[링크 : http://blog.naver.com/mindweaver/40001747916]

상속은
class DerivedClassName(BaseClassName):
class DerivedClassName(Base1, Base2, Base3):
이런식으로 상속/다중상속을 지원한다.

[링크 : http://docs.python.org/tutorial/classes.html]
Posted by 구차니
파이썬은 typeless 라고 해야 하나.. 만능형이라고 해야하나.
아무튼 전형적인 인터프리트 언어답게 변수를 알아서 인식한다.
하지만 여전히 적응이 안되는건.. 변수 선언방식.

C언어에서는 절대 용납되지 않을 문법이니까.. 익숙해져 보자.

>>> a,b = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

>>> a,b = 0,1
>>> a
0
>>> b
1

예를 들어 int형이라면
c에서는 int a = 0, b = 1; 이라고 선언해야 하지만
파이썬에서는 a,b = 0, 1 이라고 선언한다.
변수 선언과 값 할당을 확실하게 좌/우 변으로 나누어진다.

그렇다고 해서 a = 0, b = 1 이렇게는 선언할수 없다. 흐음.. 모호한 느낌
Posted by 구차니