juuuding

Chapter 03 기초 프로그램 만들기 #7, 8 본문

Python/파이썬과 40개의 작품들

Chapter 03 기초 프로그램 만들기 #7, 8

jiuuu 2023. 1. 24. 23:18

 #7 환율 변환기

 

1. 라이브러리 설치

 - currencyconverter은 환율 계산을 위한 라이브러리

pip install currencyconverter

 

2. 지원되는 통화목록 출력

#지원되는 통화 목록 출력
from currency_converter import CurrencyConverter

cc= CurrencyConverter()
print(cc.currencies)

 

 <출력 결과>

{'MXN', 'PHP', 'TRL', 'INR', 'MYR', 'ISK', 'ROL', 'THB', 'BGN', 'LTL', 'GBP', 'CYP', 'KRW', 'SGD', 'IDR', 'USD', 'AUD', 'PLN', 'JPY', 'CHF', 'RON', 'NZD', 'DKK', 'BRL', 'MTL', 'EEK', 'SKK', 'CNY', 'HRK', 'ZAR', 'ILS', 'SIT', 'LVL', 'SEK', 'RUB', 'HKD', 'EUR', 'HUF', 'TRY', 'NOK', 'CAD', 'CZK'}

 

 

3. 1달러를 원화로 변환한 결과 출력 

from currency_converter import CurrencyConverter

#최신 환율 정보로 업데이트
cc=CurrencyConverter('http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip')
print(cc.convert(1,'USD','KRW'))

 

 

4. 실시간 환율 정보 크롤링

 * 크롤링: 웹사이트, 하이퍼링크, 데이터, 정보 자원을 자동화된 방법으로 수집, 분류, 저장하는 것

- requests와 BeautifulSoup을 이용하여 사이트 정보 크롤링

#사이트 접속을 위한 모듈
import requests
from bs4 import BeautifulSoup

def get_exchange_rate(target1, target2):

    #헤더 추가. 헤더가 없으면 로봇이 접속한 것처럼 보임. 일반 브라우저를 이용하여 접속한 것처럼 보이게 함
    headers= {
        'User-Agent': 'Mozilla/5.0',
        'Content-Type': 'text/html; charset=utf-8'
    }

    #requests 라이브러리로 사이트에 접속하여 응답값을 가져옴
    response = requests.get("https://kr.investing.com/currencies".format(target1, target2),headers=headers)
    #BeautifulSoup 라이브러리를 이용하여 html로 보기 값을 찾기 좋게 함
    content = BeautifulSoup(response.content, 'html.parser')
    #마지막 환율 정보 찾기
    containers = content.find('span', {'data-test': 'instrument-price-last'})
    #환율 정보 출력
    print(containers.text)


get_exchange_rate('usd','krw')

 * 사이트 변경이 되어 크롤링이 동작하지 않음 -> 해당 사이트의 html 코드를 확인하였는데도 아직 원인을 못 찾았다.

 

+ BeautifulSoup을 사용하기 위하여 따로 beautifulsoup4 설치하여야 했다.

 pip install beautifulsoup4

 

 

 #8 쓰레드를 사용한 프로그램

 

* 쓰레드란 코드를 실행하는 하나의 동작이다. 프로그램이 커지고 해야할 일이 많아진다면 하나의 동작만을 가지고는 부족하여 쓰레드라는 방식의 프로그램을 사용해 동작을 늘린다.  

 

1. 2가지 동작이 동시에 실행

# 쓰레드 사용 모듈
import threading
import time

def thread1():
    while True:
        print('쓰레드1 동작')
        time.sleep(1.0)

# 쓰레드 설정
t1 = threading.Thread(target = thread1)
t1.start()

while True:
    print("메인 동작")
    time.sleep(2.0)

 - Ctrl-c를 누르면 키보드 인터럽트가 발생하여 메인동작은 종료하지만, 쓰레드1은 종료되지 않고 계속 실행된다. 쓰레드는 독립적으로 동작하도록 설정되어 있기 때문이다. 따라서 쓰레드1 동작을 멈추려면 쓰레기통 아이콘을 눌러 실행되고 있는 파이썬 쉘을 종료시켜야 한다.

 

 

2. 메인코드가 동작할 때에만 쓰레드 동작

import threading
import time

def thread_1():
    while True:
        print("쓰레드1 동작")
        time.sleep(1.0)

t1= threading.Thread(target = thread_1)

# 데몬 쓰레드로 설정하여 메인 동작이 실행될 때만 쓰레드를 실행하도록 함
t1.daemon = True
t1.start()


while True:
    print("메인 동작")
    time.sleep(2.0)

 

 -데몬 쓰레드는 주스레드의 작업을 돕는 보조적인 역할을 수행한다. 따라서 주스레드가 종료되면 데몬 스레드는 강제적으로 자동 종료된다.

 

+처음에 잘못 생각한 방식

  main의 while문 안에서 스레드1을 start 시키면 될 거라 생각했다. 그러나 스레드는 오직 한번만 실행할 수 있으므로 가능하지 않은 방법이다. "RuntimeError: threads can only be started once" 라는 에러가 뜬다. 

import threading
import time

def thread_1():
    while True:
        print("쓰레드1 동작")
        time.sleep(1.0)

t1= threading.Thread(target = thread_1)


while True:
    print("메인 동작")
    time.sleep(2.0)
    t1.start()

 

 

3. 다수의 쓰레드를 동작시키기

 - 1번, 2번, 메인 스레드 모두 경쟁적으로 실행하고 종료된다. 경쟁적으로 실행되려 하다 보니 동시에 실행되는 것처럼 보인다. 이것으로 여러 개의 코드를 동작시킬 수 있다.

import threading

# name과 value를 입력받아 value의 값만큼 반복
def sum(name, value):
    for i in range (0,value):
        print(f"{name} : {i} ")

# 쓰레드 생성
t1 = threading.Thread(target= sum, args = ('1번 쓰레드', 10))
t2 = threading.Thread(target =sum, args= ('2번 쓰레드', 10))

t1.start()
t2.start()

print("Main Thread")