반응형

Python Virtualenv

  • 프로젝트별 종속성 문제를 해결하기 위해서 가상환경을 제공한다.

  • 동시에 여러개의 프로젝트 진행시 각각의 파이썬 버전이 다를경우 사용한다.

  • virtualenv 환경 구성

    pip install virtualenv
    
    D:\STUDY\study_python>virtualenv py3.8-env
    created virtual environment CPython3.8.5.final.0-64 in 6461ms
      creator CPython3Windows(dest=D:\STUDY\study_python\py3.8-env, clear=False, global=False)
      seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\SDS\AppData\Local\pypa\virtualenv)        \Local\pypa\virtualenv)
        added seed packages: pip==22.2.2, setuptools==49.6.0, wheel==0.37.1
      activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
    • 1라인 : virtualenv 를 pip 를 이용해서 설치한다.

    • 3라인 : 가상환경을 생성한다.

    • 가상환경을 실행하기 위해서는 activate 명령어를 실행하면 된다. (window 의 경우 Script 폴더에 있고 리눅스인경우 bin 폴더 안에 생긴다.)

      (py3.8-env) D:\STUDY\study_python\py3.8-env\Scripts>

      가상환경을 실행하면 위와 같이 환경 이름이 앞에 붙는다.

    • 가상환경을 종료하기 위해서는 deactivate 명령어를 실행한다.

  • virtual 환경에 구성된 패키지 export

    pip freeze > req.txt
    
    req.txt
    certifi==2022.9.24
    charset-normalizer==2.1.1
    idna==3.4
    requests==2.28.1
    urllib3==1.26.12
  • req.txt 를 인스톨 하려면 다음과 같이 하면 된다.

    pip install -r req.txt
728x90
반응형
반응형

Ubuntu 에서 파이썬 설치 위치 확인

DESKTOP-MBRI3VL:~$ python --version
Python 2.7.17
DESKTOP-MBRI3VL:~$ python3 --version
Python 3.6.9

파이썬을 설치하다 보면 2.X 도 있고 3.X 도 있다. 위와 같이 각각의 버전을 확인해보면 설치된 버전을 확인할 수 있다. Ubuntu를 설치하면 기본적으로 2.7을 path 로 설정한다.

아래와 같이 명령어를 실행 하면 설치된 파이썬 목록들이 나완다. (정말 이것 저것 많다.)

DESKTOP-MBRI3VL:~$ ls /usr/bin | grep python

python-config
python2
python2-config
python2.7
python2.7-config
python3
python3-config
python3-jsondiff
python3-jsonpatch
python3-jsonpointer
python3-jsonschema
python3.6
python3.6-config
python3.6m
python3.6m-config
python3.7
python3.7m
python3m
python3m-config
x86_64-linux-gnu-python-config
x86_64-linux-gnu-python2.7-config
x86_64-linux-gnu-python3-config
x86_64-linux-gnu-python3.6-config
x86_64-linux-gnu-python3.6m-config

그래서 update-alternatives를 사용해서 파이썬에 대한 버전을 변경해보려고 한다. update-alternatives는 심볼릭 링크를 관리해 주는 리눅스 프로그램이다.

DESKTOP-MBRI3VL:~$ ls -al  /usr/bin | grep python
lrwxrwxrwx  1 root   root           26 Mar 27  2018 dh_pypy -> ../share/dh-python/dh_pypy
-rwxr-xr-x  1 root   root         1056 Apr 16  2018 dh_python2
lrwxrwxrwx  1 root   root           29 Mar 27  2018 dh_python3 -> ../share/dh-python/dh_python3
lrwxrwxrwx  1 root   root           23 Jul  2 00:56 pdb2.7 -> ../lib/python2.7/pdb.py
lrwxrwxrwx  1 root   root           23 Jun 29 20:45 pdb3.6 -> ../lib/python3.6/pdb.py
lrwxrwxrwx  1 root   root           23 Dec 10  2021 pdb3.7 -> ../lib/python3.7/pdb.py
lrwxrwxrwx  1 root   root           31 Oct 25  2018 py3versions -> ../share/python3/py3versions.py
lrwxrwxrwx  1 root   root           26 Mar 27  2018 pybuild -> ../share/dh-python/pybuild
lrwxrwxrwx  1 root   root            9 Apr 16  2018 python -> python2.7
lrwxrwxrwx  1 root   root           16 Apr 16  2018 python-config -> python2.7-config
lrwxrwxrwx  1 root   root            9 Apr 16  2018 python2 -> python2.7
lrwxrwxrwx  1 root   root           16 Apr 16  2018 python2-config -> python2.7-config
-rwxr-xr-x  1 root   root      3624880 Jul  2 00:56 python2.7
lrwxrwxrwx  1 root   root           33 Jul  2 00:56 python2.7-config -> x86_64-linux-gnu-python2.7-config
lrwxrwxrwx  1 root   root            9 Oct 25  2018 python3 -> python3.6

위에서 보면 python의 심볼릭 링크는 python2.7 로 되어있고 python3 에 대한 링크는 python3.6 으로 되어있다. 이것을 변경하려고 한다.

DESKTOP-MBRI3VL:~$ sudo update-alternatives --config python
update-alternatives: error: no alternatives for python
DESKTOP-MBRI3VL:~$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
DESKTOP-MBRI3VL:~$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2
update-alternatives: using /usr/bin/python3.6 to provide /usr/bin/python (python) in auto mode
DESKTOP-MBRI3VL:~$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.7 3
update-alternatives: using /usr/bin/python3.7 to provide /usr/bin/python (python) in auto mode

1번 라인 : python 버전을 변경하는 명령어 인데 현재는 등록되어 있는게 없기 때문에 에러가 난다.

3번 라인 : python 명령어를 2.7로 연결하고 1번으로 할당했다.

5번 라인 : python 명령어를 3.6로 연결하고 2번으로 할당했다.

7번 라인 : python 명령어를 3.7로 연결하고 3번으로 할당했다. (2.7, 3.6, 3.7 이 설치되어있었다.)

DESKTOP-MBRI3VL:~$ update-alternatives --config python
There are 3 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.7   3         auto mode
  1            /usr/bin/python2.7   1         manual mode
  2            /usr/bin/python3.6   2         manual mode
  3            /usr/bin/python3.7   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 3

다 등록을 하고 1번 라인에 썼던 명령어를 다시 실행하면 위와 같이 나와서 사용할 버전을 선택할 수 있다.

DESKTOP-MBRI3VL:~$ python --version
Python 3.7.5

버전을 확인해 보면 위와 같이 나온다.

728x90
반응형

'Development > Python' 카테고리의 다른 글

파이썬 문법 : 튜플  (0) 2023.02.27
Python 가상환경  (0) 2022.10.27
파이썬 입력값 받기  (0) 2021.08.25
파이썬 문법 : 배열 초기화  (0) 2021.08.25
Python 으로 파일 내용 변경 하기  (0) 2020.10.20
반응형

 

## 공백으로 input 값 받는 방법
data = list(map(int, input().split()))

# 결과
1 2 3
[1, 2, 3]

파이썬으로 입력값을 받을때 위와 같이 코드를 작성하면 간편하다. (주로 코딩테스트의 입력값 받을때 사용하면 된다.)

입력값이 공백이 아닌 콤마(,) 로 구분될 경우 split(",") 으로 변경해서 코드를 작성하면 된다.

 

728x90
반응형
반응형

배열을 초기화 시에 아래와 같이 사용하면 유용하게 사용가능 하다. 

# index가 필요 없는 반복문일 경우 _ 사용, 배열 초기화시 사용
array = [[0] * 3 for _ in range(10)]
print(array)

# 결과값
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

_ 는 for 문 반복시 index 가 필요없는 단순 반복을 할 경우에 사용한다.

 

728x90
반응형
반응형

잠깐 필요에 의해서 만든 소스

 

def changeStringInFile(filePath, orgValue, newValue):
    with open(filePath, "r+") as file_object:
        fileContents = file_object.read()
        newFileContents = fileContents.replace(orgValue, newValue)   
        file_object.seek(0)
        file_object.write(newFileContents)
        file_object.close()

 

파일을 오픈 한 후에 orgValue 를 찾아서 newValue 로 변경을 한다.

변경을 한 후 열었던 파일에 다시 덮어쓴다.

다시 write 할 때에 기존 파일 뒤에 append 되는것을 막기 위해서 seek(0) 를 사용한다.

 

728x90
반응형
반응형

공부하다가 과정이 좀 많아서 적어두기로 함.

 

1. 가상환경 만들기

python -m venv [이름]

ex) python -m venv my_venv

 

2. 가상환경 실행

source my_venv/bin/activate

my_venv/Scripts/activate (윈도우일 경우)

 

3. django 설치 

(3번 부터는 가상환경 안에서 모두 실행한다.)

pip install django

 

4. 프로젝트 만들기

django-admin startproject [이름] .

 

5. 데이터 베이스 만들기

python manage.py migrate

 

6. 프로젝트 실행

python manage.py runserver

 

7. 앱 만들기

python manage.py startapp [앱이름]

 

 

# Model Migration

python manage.py makemigrations [앱이름]

python manage.py migrate

728x90
반응형
반응형

Visual Studio Code 에서 Python Jupyter Notebook 실행

 

먼저 Jupyter Notebook 이 설치되어있지 않다면 다음과 같이 설치한다.

 

pip install jupyterlab

 

(참고 : https://jupyter.org/install)

 

Ctrl + Shift + P 눌러서

 

Python: Create Blank New Jupyter Notebook 선택 한다. 

 

선택을 하게 되면 다음과 같이 Jupyter Notebook 을 사용할 수 있다.

 

728x90
반응형

'Development > Python' 카테고리의 다른 글

Python 으로 파일 내용 변경 하기  (0) 2020.10.20
python django 프로젝트 시작하기  (0) 2020.10.05
[Flask]HTTP 요청에 대한 핸들러  (0) 2016.08.22
파이썬 구구단..  (0) 2016.07.25
파이썬 함수 작성시 초기값  (0) 2016.07.11
반응형

before_first_request : 웹 application 기동 이후 가장 처음에 들어오는 HTTP 요청에서만 실행

before_request : HTTP 요청이 들어올때마다 실행

after_request : HTTP 요청이 끝나고 브라우저에 응답하기 전에 실행

teardown_request : HTTP 요청 결과가 브라우저에 응답한 다음 실행

teardown_appcontext : HTTP 요청이 완전히 완료되면 실행


before_first_request, before_request는 어떠한 인자도 전달할수 없다!!

after_request는 flask.wrapper.Response 객체를 return 해야한다.


맨 상단에 # 부분은 Encoding 때문에 추가함


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf-8 -*- 
from flask import Flask
 
app = Flask(__name__)
 
@app.route("/")
def http_my_response():
    return "/"
 
@app.before_first_request
def before_first_request():
    print ("앱 기동하고 맨처음 요청만 응답")
 
@app.before_request
def before_request():
    print ("매 요청마다 실행")
 
@app.after_request
def after_request(response):
    print ("매 요청 처리되고 나서 실행")
    return response
 
@app.teardown_request
def teardown_request(exception):
    return "브라우저가 응답하고 실행"
 
@app.teardown_appcontext
def teardown_appcontext(exception):
    print ("HTTP 요청 애플리케이션 컨텍스트가 종료될때 실행")
 
if __name__ == "__main__":
    app.run(host="0.0.0.0")
cs


두번 요청에 대한 결과값


1
2
3
4
5
6
7
8
9
앱 기동하고 맨처음 요청만 응답
매 요청마다 실행
매 요청 처리되고 나서 실행
HTTP 요청 애플리케이션 컨텍스트가 종료될때 실행
127.0.0.1 - - [22/Aug/2016 22:34:31] "GET / HTTP/1.1" 200 -
매 요청마다 실행
매 요청 처리되고 나서 실행
HTTP 요청 애플리케이션 컨텍스트가 종료될때 실행
127.0.0.1 - - [22/Aug/2016 22:34:56] "GET / HTTP/1.1" 200 -
cs







728x90
반응형
반응형
1
2
3
4
5
6
7
8
9
def gugudan(number):
    result = []
    index=1
    while index<9:
        result.append(index*number)
        index = index+1
    return result
 
print(gugudan(3))
cs



Hello World 정도는 끝냈으니..

이제 구구단.. ^^



728x90
반응형

+ Recent posts