2022-05-16 기록

  • 한글로 된 경로가 있는 경우 파이참에 python3.x 다운로드해서 처리 하려고 해도 자동으로 인식 되지 않아서직접 입력해야 함
  • 버전업에 따라서 select or switch 형태의 내부 함수가 추가 (match 문법 생성)  python 3.10 이상
  • https://www.ciokorea.com/news/185423 
  • 공부 할줄 추가 해야 한다. 용법도 다행해지는건 당연하 상태
  • if / elif /else 를 경우 수가 많은 경우 대체로 사용한다.
  • default 값을 지정하고 사용을 권장
match command.split():
    case ["quit"]:
        print("Goodbye!")
        quit_game()
    case ["look"]:
        current_room.describe()
    case ["get", obj]:
        character.get(obj, current_room)
    case ["go", direction]:
        current_room = current_room.neighbor(direction)
        # The rest of your commands go here
    case _:
        # default --> 의식적으로 넣어주는 것이 정신건강에 이롭다.
        pass

출처 : https://peps.python.org/pep-0636/

 

PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org

PEP 636 – Structural Pattern Matching: Tutorial Author Daniel F Moisset Sponsor Guido van Rossum BDFL-Delegate Discussions-To Python-Dev list Status Final Type Informational Created 12-Sep-2020 Python-Version 3.10 Post-History 22-Oct-2020, 08-Feb-2021 Re

peps.python.org

 

1. 상태 

 파이썬을 2.7.5 ( Centos7 기본) 에서 2.7.14 로 업데이트 한 상태에서 python3.X 버전도 추가로 설치

설치 방법은 

https://zladnrms.tistory.com/19

 

 

[CentOS] Python 3.7 설치

기본적으로는 Python 2.7 이 설치되어있으므로, 그와 충돌을 피하기 위한 방법도 필요하다. 2.7 to 3.7 $ sudo yum install gcc openssl-devel  libffi-devel bzip2-devel $ wget https://www.python.org/ftp..

zladnrms.tistory.com

를 이용하여 마지막에

alternatives --install 를 이용한 버전 관리 처리를 추가로 진행

예)

alternatives --install /usr/bin/python python /usr/bin/python2 50

alternatives --install /usr/bin/python python /usr/bin/python3 60

 

여러 버전을 사용하기위한 설치로

설정 변경을 하려면 

alternatives --config python

으로 변경하여 사용한다.

 

까지는 좋았는데 yum 으로 설치 할 일이 생겨 설치 진행을 하니...


#yum
There was a problem importing one of the Python modules
required to run yum. The error leading to this problem was:

   No module named yum

Please install a package which provides this module, or
verify that the module is installed correctly.

It's possible that the above module doesn't match the
current version of Python, which is:
2.7.14 (default, Mar 31 2020, 02:52:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]

If you cannot solve this problem yourself, please go to
the yum faq at: 

     yum.baseurl.org/wiki/Faq

 

----

위링크도 연결 되지 않는다.

 

여러 구글링하며 찾은 글을 봤더니 2.7 버전차이라고 생각하며 복구하는 여러 방법들이

돌아 다닌다.

1. 2.4 버전 변경 --> 이는 6.0 인듯합니다. 패스

2. /usr/bin/yum --> 파일열어 경로 첫줄에 경로 변경. 하지만 이미 버전이 업된 상태에서 처리가 쉽지 않고 기존

                          상태를 원상복구 하기가 어려워 졌다.  rpm 으로 재설치도 해봤다.

                          해보는것도 괜찮음

하지만, 

기본 상태로 원복은 한번 꼬이기 시작해서 인지 잘 되지 않음...

 

찾다가 다른 싸이트에 발견한 방법이 있음

 

 

# python
Python 2.7.14 (default, Mar 31 2020, 02:52:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import sys
>>> sys.path
....경로 A

이 경로와

# env -u LD_LIBRARY_PATH python

Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import sys
>>> sys.path
....경로 B

A와 B의 상의 함에 있어 발생하는 문제로 반단이 된다고 함.

B 경로에  

'/usr/lib64/python2.7', '/usr/lib64/python2.7' ...

있다면 아래와 같이 설정을 변경해야 합니다. B 형태의 파이썬 실행 (밑줄)의 힌트로 보면

환경변수에 문제가 있음을 알수 있습니다.

 

alias yum='LD_LIBRARY_PATH=/usr/lib64 yum'

 

yum 실행을 환경변수의 구해 받기 않게 실행하게끔 하면 완료

 

개발과 환경 세팅은 참 언제나 신세계

그럼 즐프

  1. config.ini 만들기 

  2. 실행파일 가져가기

  3. 실행 테스트

변경개발시          : 파이썬 3.x , paramiko , ConfigParser, pyinstaller 설치

ini 수정 수 사용시 : ini 수정만 함, 서버스크립 작성 (1.2), tomcat war root 위치 설정확인

was : tomcat 8.5


1. 소스들

 1.1 ini 파일 생성 ( 예제 )

from configparser import ConfigParser
config = ConfigParser()
config['settings'] = {
'go': 'set -m; /home/tomcat/apache-tomcat-8.5.53/bin/startup.sh',
'stop': '/home/tomcat/apache-tomcat-8.5.53/bin/shutdown.sh',
'waslog': 'tail -f /home/tomcat/apache-tomcat-8.5.53/logs/catalina.out',
'rebilud': '/home/tomcat/bt.sh'
}

config['ssh'] = {
'id': 'root',
'pw': 'pw',
'host': '192.168.0.8',
'port': '22'
}

config['files'] = {
'upfile': 'C:/Users/torrms/Desktop/web.war',
'dwfile': '/home/tomcat/web.war'
}
with open('./config.ini', 'w') as f:
config.write(f)

 예파일  config.ini

[settings]
go = set -m; /home/tomcat/apache-tomcat-8.5.53/bin/startup.sh
stop = /home/tomcat/apache-tomcat-8.5.53/bin/shutdown.sh
waslog = tail -f /home/tomcat/apache-tomcat-8.5.53/logs/catalina.out
rebilud = /home/tomcat/bt.sh

[ssh]
id = root
pw = pw
host = 198.168.0.8
port = 22

[files]
upfile = C:/Users/torrms/Desktop/web.war
dwfile = /home/tomcat/web.war

 

 1.2  rebilud 를 위한 sh 생성 예

 - 직접 서버에서 실행권한 및 스크립트를 작성한다. 

 - war 반영 위치를 tomcat 에 설정한다. 또는 위치 확인

 - 경로는 반드시 full 경로 사용 .. 등의 사용은 안됨.

 -  예)

  > vi bt.sh

rm -rf web
mkdir web
cd web
jar xvf /home/tomcat/web.war
cd /home/tomcat
mv web.war ./bakwar/wab_20$(date +%Y%m%d_%H%M%S).war

 

 2. 실행파일 (첨부 확인) 또는 소스 (접는글 참조, 단 들여쓰기가 날라가네요 ^^)

더보기

#실행용으로 변경시 확인하세요 ^^

import paramiko
import os, sys
from configparser import ConfigParser

# ssh 명령을 수행한다.
# exit status를 리턴한다.
def ssh_execute(ssh, command, is_print=True):
# ssh 명령의 결과로 exit status를 구하는게 쉽지 않다.
# 따라서, 명령의 끝에 "mark=$?"를 출력하여,
# 최종 exit statud를 구할 수 있도록 한다.
exit_status=0
mark="ssh_helper_result_mark!!@@="
command=command+";echo " + mark + "$?"

try:
stdin, stdout, stderr = ssh.exec_command(command, get_pty=True)
except Exception as e:
print(e)
raise e

for line in stdout:
msg=line.strip('\n')
if (msg.startswith(mark)):
exit_status=msg[len(mark):]
else:
if (True == is_print):
print(line.strip('\n'))

return int(exit_status)

# sftp 상에 경로를 생성한다.
# remote 경로가 directory이면, is_dir에 True를 전달한다.
def mkdir_p(sftp, remote, is_dir=False):
dirs_ = []
if is_dir:
dir_ = remote
else:
dir_, basename = os.path.split(remote)
while len(dir_) > 1:
dirs_.append(dir_)
dir_, _ = os.path.split(dir_)

if len(dir_) == 1 and not dir_.startswith("/"):
dirs_.append(dir_) # For a remote path like y/x.txt

while len(dirs_):
dir_ = dirs_.pop()
try:
sftp.stat(dir_)
except:
print("making ... dir", dir_)
sftp.mkdir(dir_)

#https://greenfishblog.tistory.com/258
# sftp 상에 파일을 업로드한다.
# src_path에 dest_path로 업로드한다. 두개 모두 file full path여야 한다.
def file_upload(sftp, src_path, dest_path):
#mkdir_p(sftp, dest_path)
try:
sftp.put(src_path, dest_path)
except Exception as e:
print("fail to upload " + src_path + " ==> " + dest_path)
raise e
print("success to upload " + src_path + " ==> " + dest_path)
return "0"

def get_sftp(ssh):
try:
sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
except Exception as e:
print(e)
raise e
return sftp


def get_ssh(host_ip, port, id, pw):
try:
# ssh client 생성
ssh = paramiko.SSHClient()

# ssh 정책 설정
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect
ssh.connect(hostname=host_ip, port=port, username=id, password=pw)
except Exception as e:
print(e)
raise e

return ssh

# 프로세스 시작 ##################################
if __name__ == '__main__':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

parser = ConfigParser()
parser.read('config.ini')

print(parser.sections())

ip = parser.get('ssh', 'host')
port = parser.get('ssh', 'port')
id = parser.get('ssh', 'id')
pwd = parser.get('ssh', 'pw')

ssh.connect(ip,port=port, username=id, password=pwd)

# 웹서버 명령
#exitcode = ssh_execute(ssh, "cat /project/EDIP/edip.sh")
#print("result : %d" % exitcode)
go = parser.get('settings', 'go')
stop = parser.get('settings', 'stop')
waslog = parser.get('settings', 'waslog')
rebilud = parser.get('settings', 'rebilud')

#자신의 반영 파일 로컬위치
upfile = parser.get('files', 'upfile')
dwfile = parser.get('files', 'dwfile')

print(go , stop, waslog, rebilud, upfile, dwfile)

print(os.path.exists(upfile))
if os.path.exists(upfile):
print(str(os.path.getsize(upfile)/1024/1024) + " MB")
else:
print("파일이 " + upfile + "존재 하지 않습니다.")
sys.exit()

#
#https://greenfishblog.tistory.com/258

# 정지
a = ssh_execute(ssh, stop)
while True:
if a == 0:
print("정지 : %d" % a)
break

#파일 업로드

sftp = get_sftp(ssh)
res = file_upload(sftp, upfile, dwfile)
while True:
if res == "0":
print("파일업로드 : %s" % res)
break



#반영
a = ssh_execute(ssh, rebilud)
while True:
if a == 0:
print("반영 : %d" % a)
break

#재시작
a = ssh_execute(ssh, go)
while True:
if a == 0:
print("재시작 : %d" % a)
break

#로그확인
a = ssh_execute(ssh, waslog)
while True:
if a == 0:
print("result : %d" % a)
break

ssh.close()
sftp.close()

 

autorebuild.zip
8.61MB

 

3. 실행 테스트

dos 창이 뜨면서 실행 및 등등의 작업이 진행됨을 알수 있다.


보통 그냥 설치하면 될것 처럼 하더니...


Jupyter notebook/lab 구동까지 완료


그런데..?? 

들어가면 


code 에서 단순한 코드를 실행 해보려고 했는데???


lab 기준으로  [ ] 모양과 코드의 형태가 모두 흰색으로 실행하면 output 보이지 않는 경우가 발생... (노트사진임) 아래와 같이..



무언가 문제가 있다.

파이썬 코드를 실행을 웹에서 실행 못 시키고 있는거 같은데...


구동 로그를 보니...

 RuntimeWarning: coroutine 'WebSocketHandler.get' was never awaited
  super(AuthenticatedZMQStreamHandler, self).get(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

오류가 나고 있었다. 

하하 버전에 오류가 있단다...

tornado 패키지 오류


제거하고 낮은 버전 5.1.1 버전 설치 하라고 함.


서버 내리고 아래처럼 진행하고 재구동하면


pip uninstall tornado
pip install tornado==5.1.1



여러가지 시작도 전에 애먹이네...


+ Recent posts