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


Jupyter Notebook


PySerial


matplotlib

pip install wheel

pip install matplotlib


wheel


Tkinter


PyInstaller

[Python 문법]

class


예외 처리

try: ...

except: ...


File I/O

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


PySerial

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


Tkinter


PyInstaller

-. 명령창: pyinstaller test.py

=. 실행 file 생성이 끝나면 dist folder에서 결과 확인할 수 있음

-. 하나의 file로 만들기: pyinstaller --onefile test.py

=. 압축된 하나의 file로 배포가 가능함

[Python Server]

Documents


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()


urllib

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]

ModuleNotFoundError: No module named 'pip'

= pip uninstall jupyterlab

= 그 다음에 사용자\AppData\Roaming folder에 있는 Jupyter 관련 folder 모두 삭제: jupyter, python, pip folder 삭제 필요

= C:\ProgramData\jupyter folder도 삭제

= pip install jupyter을 추가 실행

[pip 명령어]

[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.