Python 사용 방법
[2022-2학기] Python Version = 3.10.8: 강의의 연속성을 위해 이 Version만 사용하고 Update하지 않습니다.
[2021-1학기] Python Version = 3.10.0
[2020-2학기] Python Version = 3.8.6
[Download]
Python
Upgrade: 최신 설치 파일을 다시 실행하면 upgrade됨
64bit 설치: 최신 Windows x86-64 executable installer를 찾아서 설치
Jupyter Notebook
pip install jupyterlab
실행: jupyter notebook
PySerial
pip install pyserial
matplotlib
pip install wheel
pip install matplotlib
wheel
pip install wheel
Tkinter
설치 확인(명령창): python -m tkinter
PyInstaller
pip install pyinstaller
[Python 문법]
class
public: 변수나 함수 앞과 뒤에 __ 넣음; 예) __var__
private: 변수나 함수 앞에만 __ 넣음; 예) __var
protected: 변수나 함수 앞에만 _ 넣음; 하지만 외부 접근이 가능해서 의미 없음
예외 처리
try 구문에서 error가 발생하면 except 구문을 실행
try: ...
except: ...
File I/O
File에 쓰기
f = open('workfile', 'w')
f.write('This is a test\n')
f.close()
Keyboard I/O
import msvcrt
n = msvcrt.kbhit() # 누르면 1, 안 누르면 0
if n: c = msvcrt.getch() # char 하나를 받기, char는 byte임
String
Python에서 string은 모두 Unicode로 표현됨
bytes(C 언어에서 char): b'test'
string -> bytes: c = s.encode() # 문자열을 숫자로 부호화하기 위해 encode() 사용
bytes -> string: s = c.decode() # bytes는 숫자 표현이므로 문자열로 다시 바꾸기 위해 decode() 사용
PySerial
PySerial은 bytes를 사용해서 통신
import serial
ard = serial.Serial('COM6', 9600)
ard.write(b'Hello, world!')
ch = ard.read(1) # bytes
ch += ard.read(ard.inWaiting())
ard.close()
PyPlot
import matplotlib.pyplot as plt
plt.ion() # interactive mode on
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.draw() # refresh figure
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.hold(True) # hold(True) is default
plt.plot([1, 2, 3, 4], [10, 40, 20, 30])
plt.show()
time
time(): Epoch 이후로 계산한 현재 시간을 초로 return
sleep(sec): sec 초만큼 실행을 멈춤
Tkinter
GUI 만들기에 사용
PyInstaller
Python code를 실행 file(*. exe)로 만들기
사용 방법
-. 명령창: pyinstaller test.py
=. 실행 file 생성이 끝나면 dist folder에서 결과 확인할 수 있음
-. 하나의 file로 만들기: pyinstaller --onefile test.py
=. 압축된 하나의 file로 배포가 가능함
[Python Server]
Documents
http.sever: https://docs.python.org/3/library/http.server.html
socketserver: https://docs.python.org/3/library/socketserver.html
http.server
from http.server import SimpleHTTPRequestHandler, HTTPServer
class MyHttpHandler(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
output = '<html><head><meta http-equiv="Content-Type" content="text/html" charset="UTF-8" /><title>Python Web Server</title></head>'
output += f'<body><p>Request: {self.path}</p>'
output += '<p>Hello, world!</p></body></html>'
self.wfile.write(output.encode())
hostName = 'localhost'
nPort = 8080
webServer = HTTPServer((hostName, nPort), MyHttpHandler)
print("Server started at http://%s:%s" %(hostName, nPort))
webServer.serve_forever()
server: server instance
path: request path
command: request command (예: GET)
urllib
URL parsing
from urllib import parse
url = 'http://www.mokwon.ac.kr/test.html?abc=12&def=34&ghi=56'
print(parse.urlsplit(url))
print(parse.parse_qs(parse.urlsplit(url).query)) # qs: query string
print(dict(parse.parse_qsl(parse.urlsplit(url).query))) # qsl: query string to list
[Python 명령어]
- Module 선택: python -m
[Python Troubleshooting]
다음과 같은 pip 실행 error: 어떤 이유로 python에서 pip 설정이 제거되었으므로(주로 pip를 upgrade할 때 생기는 실수) python 재설치 필요
ModuleNotFoundError: No module named 'pip'
Jupyter Notebook 재설치 불가
= pip uninstall jupyterlab
= 그 다음에 사용자\AppData\Roaming folder에 있는 Jupyter 관련 folder 모두 삭제: jupyter, python, pip folder 삭제 필요
= C:\ProgramData\jupyter folder도 삭제
Jupyter command `jupyter-notebook` not found.
= pip install jupyter을 추가 실행
[pip 명령어]
설치: pip install [pkg]
설치 삭제: pip uninstall [pkg]
[Hot Keys]
- Ctrl+Z: Python kernel을 종료할 때
- Ctrl+C: keyboard interrupt 걸 때
[용어]
enctype: encoding content-type
iadd: in-place add
ndarray: n-dimensional array
pip: pip installs packages
rc: runtime configuration
wheel: a built-package format that offers the advantage of not recompiling your software during every install.