파이썬 정리


- 테스트 환경 : ActivePython 2.7
http://www.activestate.com/activepython
    - Tkinter 모듈등 사용 가능



* 개발툴
Eclipse + PyDev
Jetbrains 의 PyCharm



* 주석
    한줄 : #
    범위 : """(큰따옴표 3개) 로 묶는다


* 콘솔에서 나오기 : Ctrl + Z


* *.py 파일 시작부분
#!/usr/bin/env python            #환경
# -*- coding: utf-8 -*-     #한글 쓰려면 필요


//===========
* 명령행(cmd.exe)에서 한글 깨짐 문제 해결방법
    기본 코드 페이지 = chcp 949 euc kr
    UTF-8 = chcp 65001 (UTF-8) 로 변경
    - 에러 : The system cannot write to the specified device
        - 해결방법 1 : cmd.exe /u
        - 해결방법 2 : 우상아이콘 클릭 -> 속성 -> 글꼴 : Lucida Console 선택


//===========
* 파이썬 소스를 실행파일로 변환(*.exe 만들기)
    - py2exe
http://www.py2exe.org/


//========
* 제어 - 조건(if), 순환(for)
https://wikidocs.net/20
if money:
    print("택시를 타고 가라");
else:
    print("걸어가라");

//for 배열
test_list = ['one', 'two', 'three']
for i in test_list:
    print(i)

//for 합하기
sum = 0
for i in range(1, 11):
    sum = sum + i

print(sum)    # 들여쓰기가 중요


//========
* 파일 다루기
f = open("새파일.txt", 'r')
while 1:
    line = f.readline();
    print(line);
    if not line: break
    print(line);
f.close()


//========
* 함수
def printme( str ):
    "This prints a passed string into this function"
    number = 3;
    print("str %d " % number);
    return;


//========
* 클래스
http://agiantmind.tistory.com/32
# 클래스 선언
class Guest:
    category = 'Guest'   # 클래스 내 변수 설정

    def __init__(self, num): # 생성자 / 객체 생성시 호출되며, GuestID 필요로 한다
         self.GuestID = num
 
    def __del__(self):   # 소멸자 / 객체 소멸시 호출
         print "Guest out"
 
    def printID(self):   # 메소드 / 인스턴스의 GuestID를 출력하는 메소드
         print self.GuestID


# Guest 클래스의 인스턴스 생성, 값 출력, 메소드 호출
A = Guest(3)     # 인스턴스 생성 (GuestID = 3으로 설정)
print A.category    # 인스턴스 내 변수 category 값 출력
print A.GuestID     # 인스턴스의 GuestID 값 출력
A.printID()      # 인스턴스의 printID() 메소드 호출


//==============
* 메인함수 만들기
https://www.artima.com/weblogs/viewpost.jsp?thread=4829
import sys
import getopt

def main():
    print "옵션 개수: %d" % (len(sys.argv) - 1)

    for i in range(len(sys.argv)):
        print "sys.argv[%d] = '%s'" % (i, sys.argv[i])

if __name__ == "__main__":
    main()


//==============
* GUI (Window 만들기)
http://www.tutorialspoint.com/python/python_gui_programming.htm

from Tkinter import *
import tkMessageBox
import Tkinter
from tkFileDialog   import askopenfilename

top = Tkinter.Tk()

#준비
frm1 = Tkinter.Frame() #준비 : 프레임 만들기
#frm1 = frm1
frm1.pack(fill=X, expand=1)

#라벨
Tkinter.Label(frm1, text=' Lable ').grid(row=0)#, sticky=E)

adkpath = Tkinter.Entry(frm1, width=50)
adkpath.grid(row=0, column=1)#, sticky=EW)
adkpath.insert(0, " path")

btn = Button(frm1,  text="...", command=top.quit)
btn.grid(row=0, column=2)

#버튼, 메시지 상자
def cb_hello():
   tkMessageBox.showinfo( "Hello Python", "Hello World")
btn = Tkinter.Button(frm1,  text ="Hello", command = cb_hello)
btn.grid(row=1, column=0)
#B.pack()

#파일선택 대화상자
def cb_file():
    name= askopenfilename()
    print name
#errmsg = 'Error!'
btn= Button( frm1, text='File Open', command=cb_file)
btn.grid(row=1, column=1)
#B2.pack()

#체크상자
CheckVar1 = IntVar()
chk = Checkbutton(frm1, text = "Music", variable = CheckVar1, \
                 onvalue = 1, offvalue = 0)#, height=5, width = 20)
chk.grid(row=1, column=2)
#chk.pack()

#라벨 , 글자 입력
L1 = Label( text="User Name")
L1.pack( side = LEFT)
E1 = Entry( bd =5)
E1.pack(side = RIGHT)

#메뉴
menubar = Menu(top)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=cb_hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=filemenu)
top.config(menu=menubar)

#
top.mainloop()



반응형
Posted by codens