다음은 Pythob 2.7.* 에 PyGTK 를 설치하여 실행되는 RPN 계산기 소스이다.

 

#!/usr/bin/env python

# Filename: rpnCalc.py
#           0,3
#
#   RPN Calculator using PyGTK
#   Modified from PyGTK/example/textview-basic.py

import pygtk
pygtk.require('2.0')
import gtk

class TextViewExample:
    def callback(self, widget, data=None):
        print "Hello again - %s was pressed" % data
        if data != None:
            self.textbuffer.insert(self.textbuffer.get_end_iter(), data + "\n")
               
    def enter_callback(self, widget, entry):
        entry_text = entry.get_text()
        print "Entry contents: %s\n" % entry_text
  
    def create_model(self):
        '''create the model - a ListStore'''
        self.store = gtk.ListStore(float)
        return self.store
 
    def create_columns(self, treeView):
        ''' create the columns '''
        rendererText = gtk.CellRendererText()
        rendererText.set_property('xalign', 1.0)   # work for right align
        column = gtk.TreeViewColumn(None, rendererText, text=0)
        column.set_sort_column_id(0)
        column.set_alignment(0.5)   # work for center align

        # append the column
        treeView.append_column(column)

    def reset(self, widget, entry):
        entry.set_text("")

    def calcIt(self, widget, entry):
        CONTINUE_FLAG = 1

        while CONTINUE_FLAG == 1:
            param = entry.get_text()
            tokens = self.tokenize(param)
            token_len = len(tokens)

            self.textbuffer.insert(self.textbuffer.get_end_iter(), "RPN> " + param + "\n")

            for i in range(0, token_len):
                    str = "" + tokens[i]
                    if len(str) == 0:
                        continue

                    a = str[0:1]

                    if a == 'Q' or a == 'q':
                        self.showMessage("Quit")
                        self.clear()
                        CONTINUE_FLAG = 0
                        break

                    if a in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']:
                            self.push(eval(str))
                    elif a == '+':
                            if len(str) > 1:
                                self.push(eval(str))
                            else:
                                self.push(self.pop() + self.pop())
                    elif a == '-':
                            if len(str) > 1:
                                self.push(eval(str))
                            else:
                                op2 = self.pop();
                                self.push(self.pop() - op2)
                    elif a == '*':
                         if str == "**":
                                op2 = self.pop()
                                self.push(pow(self.pop(), op2))
                         else:
                                self.push(self.pop() * self.pop())
                    elif a == '/':
                            op2 = self.pop()
                            if op2 != 0.0:
                                self.push(self.pop() / op2)
                            else:
                                self.showMessage("zero divisor popped")
                    elif a == '^':
                            op2 = self.pop()
                            self.push(pow(self.pop(), op2))
                    elif a == '=' or a == 'p':
                            listmodel = self.listView.get_model()
                            y = listmodel.get_value(listmodel.get_iter_first(), 0)
                            self.showMessage("%s" % y)
                    elif a == 'c':
                            self.showMessage("Clear")
                            self.clear()
                    else:
                            self.showMessage("Unknown Command: " + a)
            CONTINUE_FLAG = 0
            entry.set_text("")


    # push f onto value stack
    def push(self, f):
        self.store.insert(0, [f])

    # pop top value from stack
    def pop(self):
        try:
             listmodel = self.listView.get_model()
             y = listmodel.get_value(listmodel.get_iter_first(), 0)
             self.store.remove(self.store.get_iter_first())
             return y
        except:
             raise "pop error on empty stack"
        return None

    # clear stack
    def clear(self):
        self.store.clear()


    # Tokenize the input string.
    def tokenize(self, s):
        self.len = len(s)
        t = ""
        tokens = []    # list of tokens

        for i in range(0, self.len):
            c = s[i:i+1]
            if c == ' ' or c == '\t' or c == '\r' or c == '\n':
                    if len(t) > 0:
                            tokens.append(t)
                            t = ""
            elif c == '+' or c == '-':
                    if len(t) > 0:
                            tokens.append(t)
                            t = c
                    elif len(t) == 0:
                            t = c
            elif c == '*':
                    if len(t) > 1:
                            tokens.append(t)
                            tokens.append(c)
                            t = ""
                    elif len(t) == 1:
                         if t == "*":
                                tokens.append("**")
                                t = ""
                         else:
                                tokens.append(t)
                                tokens.append(c)
                                t = ""
                    elif len(t) == 0:
                            t = c
            elif c == '/' or c == '^' or c == '=' or c == 'p' or c == 'q' or c == 'Q':
                    if len(t) > 0:
                            tokens.append(t)
                            tokens.append(c)
                            t = ""
                    elif len(t) == 0:
                            tokens.append(c)
            else:
                    t += c

        if len(t) > 0:
                tokens.append(t)
                t = ""
        return tokens


    def showMessage(self, m):
        if m != None:
            self.textbuffer.insert(self.textbuffer.get_end_iter(), "%s\n" % m)


    def close_application(self, widget):
        gtk.main_quit()

    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_resizable(True) 
        window.connect("destroy", self.close_application)
        window.set_title("RPN Calculator")
        window.set_default_size(500, 300)
        window.set_border_width(0)

        box2 = gtk.VBox(False, 10)
        box2.set_border_width(10)
        window.add(box2)
        box2.show()

        hbox1 = gtk.HBox()
        box2.pack_start(hbox1, True, True, 0)
        hbox1.show()


        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        textview = gtk.TextView()
        self.textbuffer = textview.get_buffer()
        sw.add(textview)
        sw.show()
        textview.show()

        hbox1.pack_start(sw, True, True, 10)


        # create a scrollable window and integrate it into the vbox
        sw2 = gtk.ScrolledWindow()
        sw2.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        sw2.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
 
        # create a TreeView object which will work with our model (ListStore)
        store = self.create_model()
        self.listView = gtk.TreeView(store)
        self.listView.set_rules_hint(True)
        self.listView.set_headers_clickable(False)
        self.listView.set_property("headers-visible", False)
 
        # add the TreeView to the scrolled window
        sw2.add(self.listView)
 
        sw2.show()
        self.listView.show()

        # create the columns
        self.create_columns(self.listView)
        sw2.set_size_request(150, 300)
        hbox1.pack_start(sw2, False, False, 10)


        # check button to toggle editable mode
        textview.set_editable(False)
        textview.set_cursor_visible(False)
       
        hbox2 = gtk.HBox()
        box2.pack_start(hbox2, False, True, 0)
        hbox2.show()

        entry = gtk.Entry()
        entry.set_max_length(50)
        entry.connect("activate", self.enter_callback, entry)
        hbox2.pack_start(entry, True, True, 10)
        entry.show()

        hbox3 = gtk.HButtonBox()
        hbox2.pack_start(hbox3, False, False, 0)
        hbox3.show()

        btnCalc = gtk.Button("Calculate")
        btnCalc.connect("clicked", self.calcIt, entry)
        hbox3.pack_start(btnCalc, True, True, 5)
        btnCalc.set_flags(gtk.CAN_DEFAULT)
        btnCalc.grab_default()
        btnCalc.show()
       

        btnReset = gtk.Button("Reset")
        btnReset.connect("clicked", self.reset, entry)
        hbox3.pack_start(btnReset, True, True, 5)
        btnReset.set_flags(gtk.CAN_DEFAULT)
        btnReset.grab_default()
        btnReset.show()

        window.show()

def main():
    gtk.main()
    return 0      

if __name__ == "__main__":
    TextViewExample()
    main()

 

프롬프트> python rpnCalc.py

 

 

 

Posted by Scripter

댓글을 달아 주세요

Python 2.7.8 에 PyGTK 를 설치한 후, 

GTK 와 PyGTK 의 버전 알아내기

 

1. 윈도우에서 32 비트 Python 2.7.8 에 PyGTK 밑 모든 관련 파일을 한 번에 내려받아 설치하기:

http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/pygtk-all-in-one-2.22.6.win32-py2.7.msi

 

프롬프트> python
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)]'
>>> import pygtk
>>> pygtk.require('2.0')
>>> import gtk
>>> gtk.gtk_version
(2, 22, 1)
>>> gtk.pygtk_version
(2, 22, 0)

 

2. 윈도우에서 64 비트 Python 2.7.8 에 PyGTK 밑 관련 파일들을 내려받아 설치하기:

1) http://www.gtk.org/download/win64.php 에사 하나의 파일로 압축 2.22 번정르 내려 받아 폴더 C:\gtk2 에 압축  해제한후 C:\gtk2\bin 을 환경변수 PATH 에 걸어 둔다.

2) http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygtk 에서 64 비트용 pygtk, pygobject, py2cairo 들을 각각 내려받아 각가의 exe 파일을 더블클릭하여 설치한다.

 

프롬프트> python
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygtk
>>> pygtk.require("2.0")
>>> import gtk
>>> gtk.gtk_version
(2, 22, 1)
>>> gtk.pygtk_version
(2, 22, 0)
>>> import sys
>>> sys.version
'2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)]'

 

* PyGTK 의 태스트 예제: button.py

#!/usr/bin/env python

# example-start buttons buttons.py

import pygtk
pygtk.require('2.0')
import gtk

# Create a new hbox with an image and a label packed into it
# and return the box.

def xpm_label_box(parent, xpm_filename, label_text):
    # Create box for xpm and label
    box1 = gtk.HBox(False, 0)
    box1.set_border_width(2)

    # Now on to the image stuff
    image = gtk.Image()
    image.set_from_file(xpm_filename)

    # Create a label for the button
    label = gtk.Label(label_text)

    # Pack the pixmap and label into the box
    box1.pack_start(image, False, False, 3)
    box1.pack_start(label, False, False, 3)

    image.show()
    label.show()
    return box1

class Buttons:
    # Our usual callback method
    def callback(self, widget, data=None):
        print "Hello again - %s was pressed" % data

    def __init__(self):
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        self.window.set_title("Image'd Buttons!")

        # It's a good idea to do this for all windows.
        self.window.connect("destroy", lambda wid: gtk.main_quit())
        self.window.connect("delete_event", lambda a1,a2:gtk.main_quit())

        # Sets the border width of the window.
        self.window.set_border_width(10)

        # Create a new button
        button = gtk.Button()

        # Connect the "clicked" signal of the button to our callback
        button.connect("clicked", self.callback, "cool button")

        # This calls our box creating function
        box1 = xpm_label_box(self.window, "info.xpm", "cool button")

        # Pack and show all our widgets
        button.add(box1)

        box1.show()
        button.show()

        self.window.add(button)
        self.window.show()

def main():
    gtk.main()
    return 0    

if __name__ == "__main__":
    Buttons()
    main()

 

프롬프트> python button.py

 

 

 

Posted by Scripter

댓글을 달아 주세요

현재 Python 3.3 의 최신 릴리즈는 3.3.5 이고, Python 3.4 의 최신 릴리즈는 3.3.1 이다. 또한 IPython 의 최신 릴리즈는 2.1.0 이다. 

 

여기서는 윈도우용 Python 3.3.5 를 설치한 후 IPython 2.1.0 을 설치하여 사용하는데 문제가 많아 그 한 해결법을 제시한다.'(윈도우용 Python 3.4.1 의 경우에는 IPython 2.1.0 이 무리 없이 잘 설치된다.)

 

이 글에서 IPython 을 포함하여 모든 Python 확장 모듈의 설치는 모두

Unofficial Windows Binaries for Python Extension Packages

의 것을 내려받아 설치하는 것으로 간주한다.

 

우선 Python 3.3.5 인터프리터를 실행해 본다. 

프롬프트> python
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:37:12) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit() 

이번에는 IPython 인터프리터를 실행해본다.  IPython 의 실행파일은 %PYTHONPATH%\Scripts 폴더에 존재하므로 이 폴더를 환경변수 PATH 에 넣어주어야 한다.

프롬프트> ipython
Traceback (most recent call last):
  File "c:\python335\Scripts\ipython-script.py", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named 'pkg_resources'

 

위의 에러 메시지는 pkg_resources 모듈이 설치되어 있지 않다는 의미이다.

Python 3.4.1 을 설치하여 %PYTHONPATH%\Lib\site_packes 폴더에 있는 pkg_resource.py 파일을 Python 3.3.5 의 해당 폴더에 복사한 후 ipython 릏 다시 실행한다.

프롬프트> ipython
WARNING: Readline services not available or not loaded.
WARNING: Proper color support under MS Windows requires the pyreadline library.
You can find it at:
http://ipython.org/pyreadline.html
Gary's readline needs the ctypes module, from:
http://starship.python.net/crew/theller/ctypes
(Note that ctypes is already part of Python versions 2.5 and newer).

Defaulting color scheme to 'NoColor'
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:37:12) [MSC v.1600 32 bit (In
tel)]
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: exit()

 

이번에는 IPython 이 실행은 되었지만 색상이 지원되지않는다. 그래서 PyReadline 을 설치하고 다시 ipython 을 실행한다.


프롬프트> ipython
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:37:12) [MSC v.1600 32 bit (In
tel)]
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: exit()

위와 같이 IPython 2.1.0 이 잘 실행되었음을 알 수 있다.

 

64비트용 Python 3,3,5 의 경우에도 위와 같은 방법으러  IPython 2,1,9 을 설치하여 사용할 수 있다.

 

Python 3,4,1 의 경우 IPython 2.1.0 이 설치와 실행은 잘 되지만, 역시 색상은 지둰되지 않는다.

이 경우 PyReadline 을 설치하는 방법은

프롬프트> set PATH=%PYTHTHON341PATH%;%PYTHON341PATH%\Scripts;%PATH%

한 후 pip 명령으로 pyreadline 을 설치한다.

프롬프트> pip ionstall pyreadline

만일 pip 명렬으로 pyreadline 이 설치되지 않으면 Download PyReadline 에서 직법 내려받아 설치해도 된다. (32bit 용 Python 3.4.1 의 경우 이렇게 하여 성공적으로 설치하였다.)

 

참고로, Matplotlib 를 이용하기 위해서는 numpy, python-dateutil, pytz, pyparsing, six, pillow, pycairo, tornado, pyside, pyq 들이 먼저 설치되어 있어야 한다.

이제 Matplotlib 가 잘 설치되었는지 IPython 으로 테스트해 보자.

 

프롬프트> ipython -pylab

 WARNING: `-pylab` flag has been deprecated.
    Use `--matplotlib <backend>` and import pylab manually.
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AM
D64)]
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
Using matplotlib backend: TkAgg

In [1]: x = randn(10000)

In [2]: hist(x, 100)
Out[2]:
(array([   1.,    0.,    0.,    0.,    0.,    1.,    1.,    3.,    1.,
           2.,    3.,    2.,    2.,    5.,    6.,    4.,    5.,   10.,
           8.,   20.,   27.,   16.,   25.,   34.,   30.,   26.,   51.,
          60.,   70.,   66.,   86.,   97.,   88.,  108.,  118.,  140.,
         151.,  158.,  156.,  175.,  189.,  215.,  220.,  255.,  251.,
         273.,  267.,  260.,  295.,  285.,  314.,  320.,  298.,  285.,
         310.,  327.,  299.,  281.,  246.,  260.,  247.,  277.,  190.,
         199.,  186.,  187.,  206.,  139.,  135.,  131.,  126.,  100.,
         119.,   74.,   71.,   67.,   67.,   42.,   27.,   34.,   29.,
          30.,   24.,   15.,    8.,   13.,   12.,   11.,    3.,    7.,
           4.,    0.,    2.,    2.,    5.,    1.,    2.,    1.,    0.,    1.]),
 array([-3.96240846, -3.8868053 , -3.81120214, -3.73559898, -3.65999581,
        -3.58439265, -3.50878949, -3.43318633, -3.35758317, -3.28198001,
        -3.20637685, -3.13077368, -3.05517052, -2.97956736, -2.9039642 ,
        -2.82836104, -2.75275788, -2.67715471, -2.60155155, -2.52594839,
        -2.45034523, -2.37474207, -2.29913891, -2.22353574, -2.14793258,
        -2.07232942, -1.99672626, -1.9211231 , -1.84551994, -1.76991678,
        -1.69431361, -1.61871045, -1.54310729, -1.46750413, -1.39190097,
        -1.31629781, -1.24069464, -1.16509148, -1.08948832, -1.01388516,
        -0.938282  , -0.86267884, -0.78707567, -0.71147251, -0.63586935,
        -0.56026619, -0.48466303, -0.40905987, -0.3334567 , -0.25785354,
        -0.18225038, -0.10664722, -0.03104406,  0.0445591 ,  0.12016226,
         0.19576543,  0.27136859,  0.34697175,  0.42257491,  0.49817807,
         0.57378123,  0.6493844 ,  0.72498756,  0.80059072,  0.87619388,
         0.95179704,  1.0274002 ,  1.10300337,  1.17860653,  1.25420969,
         1.32981285,  1.40541601,  1.48101917,  1.55662233,  1.6322255 ,
         1.70782866,  1.78343182,  1.85903498,  1.93463814,  2.0102413 ,
         2.08584447,  2.16144763,  2.23705079,  2.31265395,  2.38825711,
         2.46386027,  2.53946344,  2.6150666 ,  2.69066976,  2.76627292,
         2.84187608,  2.91747924,  2.99308241,  3.06868557,  3.14428873,
         3.21989189,  3.29549505,  3.37109821,  3.44670137,  3.52230454,
         3.5979077 ]),
 <a list of 100 Patch objects>)

 

 

 

-pylab 옵션이 deprecate 되었다고 하니 이번에는 옵션--matplotlib 으로 실행해 보자.

프롬프트> ipython --matplotlib
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AM
D64)]
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
Using matplotlib backend: TkAgg

In [1]: from pylab import *

In [2]: x = randn(10000)

In [3]: hist(x, 100)
Out[3]:
(array([   2.,    1.,    1.,    1.,    1.,    3.,    7.,    5.,    1.,
           4.,   11.,   13.,   15.,   16.,   20.,   21.,   27.,   25.,
          31.,   34.,   47.,   47.,   62.,   70.,   68.,   79.,   98.,
         101.,  123.,  121.,  145.,  142.,  142.,  168.,  172.,  193.,
         212.,  235.,  229.,  227.,  240.,  236.,  296.,  286.,  259.,
         276.,  285.,  274.,  302.,  308.,  284.,  286.,  288.,  255.,
         251.,  234.,  215.,  198.,  216.,  183.,  192.,  175.,  175.,
         156.,  130.,  133.,  102.,  101.,   90.,   95.,   79.,   54.,
          63.,   57.,   50.,   32.,   36.,   33.,   24.,   21.,   23.,
          16.,    9.,    6.,   12.,    7.,    6.,    6.,    5.,    4.,
           1.,    4.,    2.,    2.,    2.,    1.,    3.,    0.,    0.,    1.]),
 array([-3.40718204, -3.33556225, -3.26394247, -3.19232268, -3.1207029 ,
        -3.04908311, -2.97746333, -2.90584354, -2.83422376, -2.76260398,
        -2.69098419, -2.61936441, -2.54774462, -2.47612484, -2.40450505,
        -2.33288527, -2.26126548, -2.1896457 , -2.11802592, -2.04640613,
        -1.97478635, -1.90316656, -1.83154678, -1.75992699, -1.68830721,
        -1.61668742, -1.54506764, -1.47344785, -1.40182807, -1.33020829,
        -1.2585885 , -1.18696872, -1.11534893, -1.04372915, -0.97210936,
        -0.90048958, -0.82886979, -0.75725001, -0.68563023, -0.61401044,
        -0.54239066, -0.47077087, -0.39915109, -0.3275313 , -0.25591152,
        -0.18429173, -0.11267195, -0.04105216,  0.03056762,  0.1021874 ,
         0.17380719,  0.24542697,  0.31704676,  0.38866654,  0.46028633,
         0.53190611,  0.6035259 ,  0.67514568,  0.74676546,  0.81838525,
         0.89000503,  0.96162482,  1.0332446 ,  1.10486439,  1.17648417,
         1.24810396,  1.31972374,  1.39134353,  1.46296331,  1.53458309,
         1.60620288,  1.67782266,  1.74944245,  1.82106223,  1.89268202,
         1.9643018 ,  2.03592159,  2.10754137,  2.17916115,  2.25078094,
         2.32240072,  2.39402051,  2.46564029,  2.53726008,  2.60887986,
         2.68049965,  2.75211943,  2.82373921,  2.895359  ,  2.96697878,
         3.03859857,  3.11021835,  3.18183814,  3.25345792,  3.32507771,
         3.39669749,  3.46831728,  3.53993706,  3.61155684,  3.68317663,
         3.75479641]),
 <a list of 100 Patch objects>)

 

 

 

이제 32비트용 Python 3.4.1 에서 Matplotlib 를 사용해 보자.

32비트용 Python 3.4.1 이 폴더 C:\Python34-32 에 설치된 것으로 간주한다.

먼저 명령 프롬프트에서 환경변수 PATH 를 설정한다.

프롬프트> pythonset PATH=C:\Python34-32;C:\Python34-32\Scripts;%PATH%

Pyhon 인터프리터를 실행하여 간단한 코드

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

를 입력한다.

프롬프트> python
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "c:\python34-32\lib\site-packages\matplotlib\__init__.py", line 111, in <
module>
    import dateutil
ImportError: No module named 'dateutil'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python34-32\lib\site-packages\matplotlib\__init__.py", line 113, in <
module>
    raise ImportError("matplotlib requires dateutil")
ImportError: matplotlib requires dateutil
>>> plt.plot([1,2,3,4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> plt.ylabel('some numbers')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> plt.show()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> exit()


위의 에러 메시징[서 보다 시피, 모듈 dateutil 이 없다는 에러다.

이번에는 IPython 을 실행해 본다.

프롬프트> ipython
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (In
tel)]
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: exit()

IPython 은 정상적으로 잘 실행된다.

pip 명령으로 python-dateutil 을 설치한다.

프롬프트> pip install python-dateutil
Downloading/unpacking python-dateutil
  Running setup.py (path:C:\Users\ph\AppData\Local\Temp\pip_build_ph\python-date
util\setup.py) egg_info for package python-dateutil

Requirement already satisfied (use --upgrade to upgrade): six in c:\python34-32\
lib\site-packages (from python-dateutil)
Installing collected packages: python-dateutil
  Running setup.py install for python-dateutil

Successfully installed python-dateutil
Cleaning up...

 

다시 Pyhon 인터프리터를 실행하여 앞에서 제시했던 간단한 코드를 입력해 본다.

프롬프트> python
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "c:\python34-32\lib\site-packages\matplotlib\__init__.py", line 125, in <
module>
    import pyparsing
ImportError: No module named 'pyparsing'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python34-32\lib\site-packages\matplotlib\__init__.py", line 127, in <
module>
    raise ImportError("matplotlib requires pyparsing")
ImportError: matplotlib requires pyparsing
>>> plt.plot([1,2,3,4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> plt.ylabel('some numbers')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> plt.show()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'plt' is not defined
>>> exit()

 

위의 에러 메시징[서 보다 시피, 이번에는 모듈 pyparsing 이 없다는 에러다.

그래서 pip 명령으로 pyparsing 을 설치한다.

프롬프트> pip install pyparsing
Downloading/unpacking pyparsing
  Running setup.py (path:C:\Users\ph\AppData\Local\Temp\pip_build_ph\pyparsing\s
etup.py) egg_info for package pyparsing

Installing collected packages: pyparsing
  Running setup.py install for pyparsing

Successfully installed pyparsing
Cleaning up...

 

python-dateutil 과 ptparsing 이 설치되었으니 다시 Pyhon 인터프리터를 실행하여 앞에서 제시했던 간단한 코드를 입력해 본다.

프롬프트> python
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x045BE530>]
>>> plt.ylabel('some numbers')
<matplotlib.text.Text object at 0x047160B0>
>>> plt.show()

위의 명령이 모두 수행되어 아래 처럼 Matplotlib 에 의한 그래프 창이 성공적으로 뜬다.

 


 

이번에는 좌표평면의 네 점 (1, 1), (2, 4), (3, 9), (4, 16) 에 (속이 채워진) 뿕은 색의 굵은 점을 찍어본다.

>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3,4], [1,4,9,16], 'ro')
[<matplotlib.lines.Line2D object at 0x042EE3B0>]
>>> plt.axis([0, 6, 0, 20])
[0, 6, 0, 20]
>>> plt.show()

 

 

 

이번에는 NumPy 모듈을 이용하여, 한 좌표평면의 세 함수 y = x, y = x^2, y = x^3 의 그래프를 그려 보자.

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> t = np.arange(0., 5., 0.2)
>>> plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[<matplotlib.lines.Line2D object at 0x04716410>, <matplotlib.lines.Line2D object
 at 0x047169F0>, <matplotlib.lines.Line2D object at 0x047160F0>]
>>> plt.show()

 

 

 

* 이 외에도 Matplotlib 튜토리얼의 다른 예제 들도 잘 실행됨을 확인하였다.

 

 

Posted by Scripter

댓글을 달아 주세요