외부 인터넷 접속이 되지 않는 환경에서  모듈을 설치하는 방법 입니다.

자주 사용하는 MySQL 모듈을 기준으로 설명드리겠습니다. 

1. https://pypi.org/ 사이트에 접속하여 다운받을 모듈과 버전 정보를 결정합니다.

    - https://pypi.org/project/PyMySQL/

    - https://pypi.org/project/PyMySQL/#history 버전 정보를 확인합니다.

 

2.  cmd를 실행하여 아래와 같이 모듈 정보를 입력합니다.

pip download -d ./ PyMySQL==1.0.1

    위와 같이 실행시 SSL  오류가 발생하며 다운로드가 안된다면 아래와 같이 실행합니다.

pip --trusted-host pypi.org --trusted-host files.pythonhosted.org download -d ./ PyMySQL

 

    - 버전을 명시하지 않을 경우 최신 버전이 다운로드 됩니다.

 

3. 파일을 폐쇄망으로 이동시킵니다.

 

4. 아래 명령어를 통해서 다운받은 모듈을 설치합니다.

pip install --no-index --find-links=./ PyMySQL          << 특정 위치의 모듈을 설치할 경우

pip install --no-index --find-links=./ PyMySQL==1.0.2   << 특정 버전의 모듈을 설치할 경우

pip install --no-index PyMySQL                          << 모듈이 위치한 폴더에서 실행할 경우

 

5. 설치된 모듈과 버전 정보를 확인합니다.

pip list

✳️ 첨부 파일은 Visual Studio 2017 프로젝트 파일입니다.

Python_Windows_Service.7z
0.09MB

Python으로 제작한 프로그램을 Windows Service로 만드는 가장 확실한 방법 입니다. 

준비물 : 

1. nssm : https://nssm.cc/download

 

NSSM - the Non-Sucking Service Manager

NSSM - the Non-Sucking Service Manager Windows 10, Server 2016 and newer 2017-04-26: Users of Windows 10 Creators Update or newer should use prelease build 2.24-101 or any newer build to avoid an issue with services failing to start. If for some reason you

nssm.cc

➔ 테스트 Project 파일과 함께 첨부해 놓았으나 최신 버전이 필요하시면 위 링크에서 다운로드 하시면 됩니다.

 

Service 등록 절차

✔️ Python 예제 프로그램

#_*_ coding: utf-8 _*_
import os
import sys
import time
import logging
from datetime import datetime, timedelta

def init():
    current_directory = os.path.dirname(os.path.realpath(__file__)) # .py 파일 위치
    current_log_directory = os.path.join(current_directory, "Log")  # 생성할 로그 폴더
    try:
        if not os.path.exists(current_log_directory):   # 로그 폴더 존재여부 검사
            os.makedirs(current_log_directory)          # 폴더 생성
    except OSError:
        print('----------------- Error -----------------')
        return -1

    # 로그파일 설정
    now_date_str = datetime.now().strftime('%Y%m%d_%H%M%S') # 현재 시간을 파일명으로 사용
    errorlogfilename = os.path.join(current_log_directory , "Log_%s.log" % (now_date_str))  # 로그파일의 전체 경로

    # 로그파일 생성
    logging.basicConfig(
        filename=errorlogfilename, 
        level=logging.DEBUG, 
        format='[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'
    )
    return 1

def main():

    # 1초마다 로그파일에 현재 시간을 기록
    for i in range(10):
        out_message = "Now Time : %s" % (datetime.now().strftime('%Y-%m-%d_%H:%M:%S'))
        logging.info("Now Time : %s" % (out_message))
        print("Now Time : %s" % (out_message))
        time.sleep(1)

    return

if __name__ == '__main__':
    if (init() >= 1):
        while True:
            main()
            time.sleep(10)  # 10초마다 main() 함수 실행
    else:
        print("Exit")

✔️ 관리자 권한으로 CMD를 실행하여 nssm이 보관된 폴더로 이동합니다.

✔️ nssm install [서비스명]을 입력합니다.

 

✔️ Path : Python 실행파일을 선택합니다. (Startup directory는 자동으로 채워집니다.)

     ex) C:\Users\kirum\AppData\Local\Programs\Python\Python39\python.exe

✔️ Arguments : xxxx.py 파일을 전체 경로를 입력합니다.

     ex) D:\T\Python_Windows_Service\Python_Windows_Service\Python_Windows_Service.py

✔️ Install service 클릭

 

✔️ 정상적으로 Service가 등록되었으며 시작/중지 모두 정상적으로 작동합니다.

안녕하세요. 

주식 정보를 수집할 때 사용한 파이썬 소스 공유 드립니다.

 

원하시는 분이 계셔서 공유하게 되었습니다.


책하나 사서 공부 했기에 , 구조가 이쁘지 않을 수 있습니다. 감안하고 받아 주세요


이클립스 프로젝트로 첨부 합니다.


Stock_Crawling 2.7z


>> 프로젝트 구조



Excel 파일을 읽어 DB에 insert 하는 Python 소스 공유 드립니다.

Python 3.6, Eclipse 에서 작업 하였습니다.


> Eclipse Project : 엑셀 파일을 읽어 DB에 저장 


- main.py : 메인 함수

- ClsDB.py : db 작업

- ClsLogHandler.py : Excel_Insert_Err_Log 파일에 오류 로그 저장



> Python Module : 아래 2가지 모듈은 추가로 설치하셔야 합니다.

- PyMySQL : mysql DB 처리 관련 모듈, https://github.com/PyMySQL/PyMySQL

- openpyxl :  Excel 처리 모듈 , http://openpyxl.readthedocs.io/en/default/



> DB Table

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE `TBL_STOCK` (
  `type_code` varchar(10NOT NULL,
  `basic_date` date NOT NULL,
  `open_value` float DEFAULT NULL COMMENT '시가',
  `high_value` float DEFAULT NULL COMMENT '고가',
  `low_value` float DEFAULT NULL COMMENT '저가',
  `close_value` float DEFAULT NULL COMMENT '종가',
  `adj_close_value` float DEFAULT NULL COMMENT '수정 주가',
  `volume_value` float DEFAULT NULL COMMENT '거래량',
  PRIMARY KEY (`type_code`,`basic_date`)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
cs


> Source File Excel_Insert.zip


문의 및 의견은 댓글로 달아 주시길 바랍니다. 

코스피 증시 데이터를 수집하면서, CSV 파일을 DB에 등록할 필요가 있어 만들었습니다.


> 모듈 설명 : https://docs.python.org/3/library/csv.html


> Eclipse 에서 만들었으며, Pythoh 3.6 을 사용하였습니다.


  - main.py : CSV파일을 Read

  - DBCls : DB 처리

  - ClsLogHandler.py : 파일에 오류 로그 기록 


> Source File :        CSV_Insert.zip


질문이나 의견은 댓글로 부탁 드립니다. ^^


+ Recent posts