외부 프로그램을 실행하고 그 표준 출력/에러를 텍스트 컨트롤에 표시하는 어플의 Template입니다.


template2.py
# -*- coding: utf-8 -*-
#!/usr/bin/python
 
import wx
import subprocess
import threading
import sys
 
COMMAND_PATH = "test.py" # 실행할 외부 프로그램 경로

def stdout_thread(pipe, callback):
    for line in iter(pipe.stdout.readline, b''):
        callback(line.rstrip())

def exec_command(cmd, callback, cwd=None):
    p = subprocess.Popen(cmd, 
                         stdout=subprocess.PIPE, 
                         stderr=subprocess.STDOUT, cwd=cwd)
    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p, callback))

    out_thread.start()
 
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size = (480, 320),
            style = wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
             
        vbox = wx.BoxSizer(wx.VERTICAL)

        self.tc = wx.TextCtrl(self, 1, size = (-1, 200), style = wx.TE_MULTILINE)
        vbox.Add(self.tc, 0, wx.EXPAND | wx.ALL)

        self.SetSizer(vbox, True)
        self.Layout()
         
def callback_stdout(msg):
    print("}}} " + msg)
    frame.tc.AppendText(msg + "\n")
             
app = wx.App(False)
frame = MainWindow(None, -1, u"Title")
frame.Show(1)

exec_command([sys.executable, COMMAND_PATH], callback_stdout)

app.MainLoop()


test.py
# -*- coding: utf-8 -*-
#!/usr/bin/python

import sys

print "blah;blah;"
sys.stdout.flush()


[주의사항] 실행하려는 외부 프로그램이 python 코드일 때, 외부 프로그램에서 메세지 출력 후 sys.stdout.flush()를 해줘야 메세지가 그때 그때 출력된다. 그렇지 않으면 메세지가 마지막에 한꺼번에 출력된다.


template2.py 실행 화면


 


<테스트 환경>
OS : Windows 7
Python 버전 : 2.7
wxPython 버전 : 2.8.12.1


,

파이썬에서 문자열은 바이트 코드와 유니코드로 나뉜다.


바이트 코드는 euc-kr, UTF–8 등과 같이 특정 인코딩이 적용된 문자열을 말한다. 파이썬에서 유니코드는 어떤 특정 인코딩에 속하지 않는 유니버셜한 어떤 것을 나타낸다. (다른 언어에서 흔히 UTF–8을 유니코드로 일컫는 것과는 다름에 유의)

  • 유니코드 >>> 바이트 코드로 변환하기 위해서는 encode() 함수가 사용된다.

  • 바이트 코드 >>> 유니코드로 변환하기 위해서는 decode() 함수가 사용된다.

    str = ustr.encode("UTF–8") # 유니코드에서 UTF–8 바이트 코드로 변환 ustr = str.decode("UTF–8") # UTF–8 바이트 코드에서 유니코드로 변환

  • type() 함수를 사용하여 어떤 문자열이 유니코드인지 바이트 코드인지 알아낼 수 있다.

    print type(str) # 바이트 코드일 경우
    -> <type 'str'>
    
    print type(ustr) # 유니코드일 경우
    -> <type 'unicode'>
    


소스 코드 상에서 대입시,


[1]

# -*- coding: utf-8 -*-

myStr = "가나다"

myStr의 타입 -> utf-8의 <type 'str'>

[2]

# -*- coding: cp949 -*-

myStr = "가나다"

myStr의 타입 -> cp949의 <type 'str'>

[3]

myStr = u"가나다"

myStr의 타입 -> <type 'unicode'>

'# -*- coding: ~' 을 붙이지 않을 경우, 시스템 로케일인 cp949의 <type 'str'>로 적용되어야 할 것 같은데, 실제 테스트 결과는 utf-8로 적용된다??


[참고] 이것은 파이썬 2.X 대에서 적용되는 내용이고, 파이썬 3.X 대에서는 방식이 약간 달라지게 되는데...


테스트 환경
- OS : Windows 7
- Python 버전 : 2.7


,

위의 두 글을 참고하면 웹페이지의 특정 class에 해당하는 부분을 추출하여 텔레그램 채널로 보내는 것이 가능하다. (두둥)


Python 2 :
# -*- coding: utf-8 -*-
  
import requests
from bs4 import BeautifulSoup
    
r = requests.get('http://httpbin.org')
   
# beautiful soup 초기화
soup = BeautifulSoup(r.text, "html.parser")
   
# class로 찾기
mr = soup.find(class_="bash")
result = mr.get_text()
result_utf8 = result.encode("UTF-8")
  
# 텔레그램 채널로 전송
url = "https://api.telegram.org/bot<텔레그램 봇 토큰>/sendMessage"
headers = {"Content-type": "application/json"}
params = '{"chat_id": "@<채널 ID>", "text": "텍스트 추출 : %s"}' % result_utf8
r = requests.post(url, headers = headers, data = params)
   
print(r.text)

Python 3 :
# -*- coding: utf-8 -*-
  
import requests
from bs4 import BeautifulSoup
    
r = requests.get('http://httpbin.org')
   
# beautiful soup 초기화
soup = BeautifulSoup(r.text, "html.parser")
   
# class로 찾기
mr = soup.find(class_="bash")
result = mr.get_text()

# 텔레그램 채널로 전송
url = "https://api.telegram.org/bot<텔레그램 봇 토큰>/sendMessage"
headers = {"Content-type": "application/json"}
params = '{"chat_id": "@<채널 ID>", "text": "텍스트 추출 : %s"}' % result
r = requests.post(url, headers = headers, data = params.encode("UTF-8"))
   
print(r.text)


테스트 환경
 - OS : Windows 7
 - Python 버전 : 2.7, 3.6


,

사전 준비사항

  1. app template을 사용하여 프로젝트를 생성한다.


  2. seesaw 모듈 사용을 위해서 project.clj 파일의 dependencies 부분에 아래와 같이 추가해준다. (버전은 참고사이트에서 최신 버전을 확인하자)

    :dependencies [[org.clojure/clojure "1.8.0"] [seesaw/seesaw "1.4.5"]]
    


사용 예제


다음은 간단한 윈도우 창을 표시하는 예제이다.

(ns web.core
   (:gen-class)
   (:require [seesaw.core :as seesaw]))
(def window (seesaw/frame
   :title "First Example"
   :content "hello world"
   :width 200
   :height 50))
(defn -main
   [& args]
   (seesaw/show! window))


참고 사이트

,

사전 준비사항


Atom 에디터에서 Markdown -> 마인드맵 변환하기 위해서는 markdown-mindmap 패키지 설치가 필요하다.


사용 방법


아래와 같이 헤드라인 요소를 사용하여 작성한 내용을 마인드맵으로 변환할 수 있다. <h1> ~ <h6>까지만 존재하므로 최대 깊이는 6으로 제한된다.

# Root Node
## Node 1
### Node 1-1
### Node 1-2
## Node 2
### Node 2-1


Packages 메뉴에서 Mindmap view를 켜면 아래와 같이 변환된 내용을 볼 수 있다.



,