Python

wwiki
이동: 둘러보기, 검색

python2[편집 | 원본 편집]

pip 설치[편집 | 원본 편집]

$ sudo apt install python-pip

패키지 설치[편집 | 원본 편집]

$ python -m pip install 패키지명

python3[편집 | 원본 편집]

https://docs.python.org/ko/3/howto/index.html

pip3 설치[편집 | 원본 편집]

$ apt install python3-pip

패키지 설치[편집 | 원본 편집]

$ sudo pip3 install 패키지명

자습서[편집 | 원본 편집]

모듈[편집 | 원본 편집]

출처: https://docs.python.org/ko/3.8/tutorial/modules.html

파이썬은 정의들을 파일에 넣고 스크립트나 인터프리터의 대화형 모드에서 사용할 수 있는 방법을 제공합니다. 그런 파일모듈 이라고 부릅니다;

fibo.py

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

이제 파이썬 인터프리터에 들어가서 이 모듈을 다음과 같은 명령으로 임포트 합니다:

>>> import fibo
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

함수를 자주 사용할 거라면 지역 이름으로 대입할 수 있습니다:

>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

모듈 더 보기[편집 | 원본 편집]

https://docs.python.org/ko/3.8/tutorial/modules.html#more-on-modules

임포트되는 모듈 이름은 임포트하는 모듈의 전역 심볼 테이블에 들어갑니다.

모듈에 들어있는 이름(함수)들을 직접 임포트하는 모듈의 심볼 테이블로 임포트하는 import 문의 변종이 있습니다. 예를 들어:

>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

모듈이 정의하는 모든 이름을 임포트하는 변종도 있습니다:

>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

이것은 밑줄 (_) 로 시작하는 것들을 제외한 모든 이름을 임포트 합니다. 권장하지는 않는 것으로 보인다.


모듈 이름 다음에 as 가 올 경우, as 다음의 이름을 임포트한 모듈에 직접 연결합니다.

>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

fib 별칭으로 사용할 수 있는 것으로 보인다. from을 써서 비슷한 효과를 낼 때도 사용할 수 있습니다:

>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
모듈을 스크립트로 실행하기[편집 | 원본 편집]

https://docs.python.org/ko/3.8/tutorial/modules.html#executing-modules-as-scripts


여러분이 파이썬 모듈을 이렇게 실행하면

python fibo.py <arguments>

모듈에 있는 코드는, 그것을 임포트할 때처럼 실행됩니다. 하지만 __name__"__main__" 로 설정됩니다. 다음 코드를 모듈의 끝에 붙여서

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

파일을 임포트할 수 있는 모듈뿐만 아니라 스크립트로도 사용할 수 있도록 만들 수 있다. 모듈이 임포트될 때, 코드는 실행되지 않습니다:

>>> import fibo
>>>
모듈 검색 경로[편집 | 원본 편집]

https://docs.python.org/ko/3.8/tutorial/modules.html#the-module-search-path

spam 이라는 이름의 모듈이 임포트될 때, 인터프리터는 먼저 그 이름의 내장 모듈을 찾습니다. 발견되지 않으면, 변수 sys.path 로 주어지는 디렉터리들에서 spam.py 라는 이름의 파일을 찾습니다. sys.path는 다음 위치들로 초기화됩니다.

  • 입력 스크립트를 포함하는 디렉터리 (또는 파일이 지정되지 않았을 때는 현재 디렉터리).
  • PYTHONPATH (디렉터리 이름들의 목록, 셸 변수 PATH 와 같은 문법).
  • 설치 의존적인 기본값

dir() 함수[편집 | 원본 편집]

https://docs.python.org/ko/3.8/tutorial/modules.html#the-dir-function

모듈이 정의하는 이름들을 찾는다. 문자열 리스트를 반환한다.

인자가 없으면, dir() 는 현재 정의한 이름들을 나열합니다

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

모든 형의 이름을 나열한다는 것에 유의해야 합니다: 변수, 모듈, 함수, 등등.


내장 함수와 변수들의 이름을 나열하지 않습니다. 그것들의 목록을 원한다면, 표준 모듈 builtins 에 정의되어 있습니다

>>> import builtins
>>> dir(builtins)  
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
 '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
 'zip']

패키지[편집 | 원본 편집]

https://docs.python.org/ko/3.8/tutorial/modules.html#packages

패키지는 “점으로 구분된 모듈 이름” 를 써서 파이썬의 모듈 이름 공간을 구조화하는 방법입니다. 예를 들어, 모듈 이름 A.BA 라는 이름의 패키지에 있는 B 라는 이름의 서브 모듈을 가리킵니다. 모듈의 사용이 다른 모듈의 저자들이 서로의 전역 변수 이름들을 걱정할 필요 없게 만드는 것과 마찬가지다.

음향 파일과 과 음향 데이터의 일관된 처리를 위한 모듈들의 컬렉션 (“패키지”) 을 설계하길 원한다고 합시다.

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

패키지를 임포트할 때, 파이썬은 sys.path 에 있는 디렉터리들을 검색하면서 패키지 서브 디렉터리를 찾습니다.

파이썬이 디렉터리를 패키지로 취급하게 만들기 위해서 __init__.py 파일이 필요합니다. __init__.py 는 그냥 빈 파일일 수 있지만, 패키지의 초기화 코드를 실행하거나 뒤에서 설명하는 __all__ 변수를 설정할 수 있습니다.

패키지 사용자는 패키지로부터 개별 모듈을 임포트할 수 있습니다, 예를 들어

import sound.effects.echo

다음처럼 전체 이름으로 참조되어야 합니다.

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

다른 방법으로

from sound.effects import echo

이제 간단하게 다음처럼 사용할 수 있다.

echo.echofilter(input, output, delay=0.7, atten=4)

또 다른 방법은 원하는 함수나 변수를 직접 임포트 할 수도 있다.

from sound.effects.echo import echofilter

함수를 직접 사용할 수 있게 만들어 준다.

echofilter(input, output, delay=0.7, atten=4)

설정 및 사용법[편집 | 원본 편집]

출처: https://docs.python.org/ko/3.8/using/cmdline.html#command-line

Command line과 환경변수[편집 | 원본 편집]

Command line[편집 | 원본 편집]

$ python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
$ python myscript.py
인터페이스 옵션[편집 | 원본 편집]

인터프리터 인터페이스는 유닉스 셸의 인터페이스와 비슷하지만, 몇 가지 추가 호출 방법을 제공합니다:

  • 명령을 입력하라는 프롬프트를 준 후 EOF(파일 끝 문자, 유닉스에서는 Ctrl-D, 윈도우에서는 Ctrl-Z, Enter로 만들 수 있습니다)가 읽힐 때까지 실행합니다.
  • 파일 이름 인자나 파일을 표준 입력으로 사용해서 호출하면, 해당 파일에서 스크립트를 읽고 실행합니다.
  • 디렉터리 이름 인자로 호출되면, 해당 디렉터리에서 적절히 이름 붙은 스크립트를 읽고 실행합니다.
  • -c command 로 호출되면, command로 주어지는 파이썬 문장을 실행합니다.
  • -m module-name 으로 호출되면, 주어진 모듈을 파이썬 모듈 경로에서 찾은 후에 스크립트로 실행합니다.
-c <command>[편집 | 원본 편집]

command 의 파이썬 코드를 실행합니다. command 는 개행 문자로 구분된 하나 이상의 문장일 수 있다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 "-c" 가 되고, 현재 디렉터리를 sys.path 의 시작 부분에 추가합니다

-m <module-name>[편집 | 원본 편집]

제공된 이름의 모듈을 sys.path 에서 검색하고 그 내용을 __main__ 모듈로서 실행합니다.

인자가 모듈 이름이기 때문에, 파일 확장자(.py)를 주지 않아야 합니다.

패키지 이름(이름 공간 패키지 포함)도 허용됩니다. 일반 모듈 대신 패키지 이름이 제공되면, 인터프리터는 <pkg>.__main__ 을 메인 모듈로 실행합니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 모듈 파일의 전체 경로가 됩니다.

<script>[편집 | 원본 편집]

script 는 파이썬 파일이나 __main__.py 파일이 들어있는 디렉터리나 __main__.py 파일을 포함하는 zip 파일을 가리키는 파일 시스템 경로(절대나 상대)여야 합니다.

환경변수[편집 | 원본 편집]

PYTHONHOME[편집 | 원본 편집]

표준 파이썬 라이브러리의 위치를 변경합니다. 기본값은 /usr/local 입니다.

PYTHONPATH[편집 | 원본 편집]

모듈 파일의 기본 검색 경로를 보강합니다. 유닉스에서는 콜론, 윈도우에서는 세미콜론.

웹 크롤링[편집 | 원본 편집]

Selenium

string[편집 | 원본 편집]

split[편집 | 원본 편집]

https://www.w3schools.com/python/ref_string_split.asp

trim[편집 | 원본 편집]

https://www.w3schools.com/python/ref_string_strip.asp

length[편집 | 원본 편집]

substring[편집 | 원본 편집]

문자열은 배열과 같으므로 다음과 같이 접근이 가능하다.

-는 negative index로 뒤에서 5번째에서 뒤에서 세번째까지의 문자열을 구할 수도 있다.

string[2:5]

string[-5:-3]

built in functions[편집 | 원본 편집]

len[편집 | 원본 편집]

https://www.w3schools.com/python/ref_func_len.asp

Dictionary[편집 | 원본 편집]

https://www.w3schools.com/python/python_dictionaries.asp

List[편집 | 원본 편집]

a = [1, 2, 3]

append[편집 | 원본 편집]

del[편집 | 원본 편집]

delete by index(1 base)

remove[편집 | 원본 편집]

remove by value

a.remove(3)

Datetime[편집 | 원본 편집]

https://www.w3schools.com/python/python_datetime.asp

for loop[편집 | 원본 편집]

https://www.w3schools.com/python/python_for_loops.asp

file[편집 | 원본 편집]

delete[편집 | 원본 편집]

https://www.w3schools.com/python/python_file_remove.asp

에러[편집 | 원본 편집]

UnicodeDecodeError: 'ascii' codec can't decode byte[편집 | 원본 편집]

import sys 이후에 다음 코드 추가

reload(sys)
sys.setdefaultencoding('utf-8')

외부링크[편집 | 원본 편집]

문서[편집 | 원본 편집]

https://docs.python.org/ko/3/

lexical analyzer[편집 | 원본 편집]

https://docs.python.org/ko/3/reference/lexical_analysis.html

리터럴[편집 | 원본 편집]

https://docs.python.org/ko/3/reference/lexical_analysis.html#literals