주 메뉴 열기

wwiki β

바뀜

Python

13,670 바이트 추가됨, 2023년 11월 16일 (목) 23:30
자습서
== 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 pip pip3 install 패키지명 == 자습서 ===== 모듈 ===출처: https://docs.python.org/ko/3.8/tutorial/modules.html 파이썬은 정의들을 파일에 넣고 스크립트나 인터프리터의 대화형 모드에서 사용할 수 있는 방법을 제공합니다. 그런 <u>파일</u>을 ''모듈'' 이라고 부릅니다; fibo.py<syntaxhighlight lang="python3"># 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</syntaxhighlight>이제 파이썬 인터프리터에 들어가서 이 모듈을 다음과 같은 명령으로 임포트 합니다:<syntaxhighlight lang="py3">>>> import fibo</syntaxhighlight><syntaxhighlight lang="py3">>>> 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'</syntaxhighlight>함수를 자주 사용할 거라면 지역 이름으로 대입할 수 있습니다:<syntaxhighlight lang="py3">>>> fib = fibo.fib>>> fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</syntaxhighlight> ==== 모듈 더 보기 ====https://docs.python.org/ko/3.8/tutorial/modules.html#more-on-modules 임포트되는 모듈 이름은 임포트하는 모듈의 전역 [https://ko.wikipedia.org/wiki/심볼_테이블 심볼 테이블]에 들어갑니다. 모듈에 들어있는 이름(함수)들을 직접 임포트하는 모듈의 심볼 테이블로 임포트하는 <code>import</code> 문의 변종이 있습니다. 예를 들어:<syntaxhighlight lang="py3">>>> from fibo import fib, fib2>>> fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</syntaxhighlight>모듈이 정의하는 모든 이름을 임포트하는 변종도 있습니다:<syntaxhighlight lang="py3">>>> from fibo import *>>> fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</syntaxhighlight>이것은 밑줄 (<code>_</code>) 로 시작하는 것들을 제외한 모든 이름을 임포트 합니다. 권장하지는 않는 것으로 보인다.  모듈 이름 다음에 <code>as</code> 가 올 경우, <code>as</code> 다음의 이름을 임포트한 모듈에 직접 연결합니다.<syntaxhighlight lang="py3">>>> import fibo as fib>>> fib.fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</syntaxhighlight>fib 별칭으로 사용할 수 있는 것으로 보인다. <code>from</code>을 써서 비슷한 효과를 낼 때도 사용할 수 있습니다:<syntaxhighlight lang="py3">>>> from fibo import fib as fibonacci>>> fibonacci(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</syntaxhighlight> ===== 모듈을 스크립트로 실행하기 =====https://docs.python.org/ko/3.8/tutorial/modules.html#executing-modules-as-scripts  여러분이 파이썬 모듈을 이렇게 실행하면<syntaxhighlight lang="py3">python fibo.py <arguments></syntaxhighlight>모듈에 있는 코드는, 그것을 임포트할 때처럼 실행됩니다. 하지만 <code>__name__</code> 은 <code>"__main__"</code> 로 설정됩니다. 다음 코드를 모듈의 끝에 붙여서<syntaxhighlight lang="py3">if __name__ == "__main__": import sys fib(int(sys.argv[1]))</syntaxhighlight>파일을 임포트할 수 있는 모듈뿐만 아니라 스크립트로도 사용할 수 있도록 만들 수 있다. 모듈이 임포트될 때, 코드는 실행되지 않습니다:<syntaxhighlight lang="py3">>>> import fibo>>></syntaxhighlight> ===== 모듈 검색 경로 =====https://docs.python.org/ko/3.8/tutorial/modules.html#the-module-search-path <code>spam</code> 이라는 이름의 모듈이 임포트될 때, 인터프리터는 먼저 그 이름의 내장 모듈을 찾습니다. 발견되지 않으면, 변수 <code>sys.path</code> 로 주어지는 디렉터리들에서 <code>spam.py</code> 라는 이름의 파일을 찾습니다. sys.path는 다음 위치들로 초기화됩니다. * 입력 스크립트를 포함하는 디렉터리 (또는 파일이 지정되지 않았을 때는 현재 디렉터리).* <code>PYTHONPATH</code> (디렉터리 이름들의 목록, 셸 변수 <code>PATH</code> 와 같은 문법).* 설치 의존적인 기본값 ==== dir() 함수 ====https://docs.python.org/ko/3.8/tutorial/modules.html#the-dir-function 모듈이 정의하는 이름들을 찾는다. 문자열 리스트를 반환한다. 인자가 없으면, <code>dir()</code> 는 현재 정의한 이름들을 나열합니다<syntaxhighlight lang="py3">>>> a = [1, 2, 3, 4, 5]>>> import fibo>>> fib = fibo.fib>>> dir()['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']</syntaxhighlight>모든 형의 이름을 나열한다는 것에 유의해야 합니다: 변수, 모듈, 함수, 등등.  내장 함수와 변수들의 이름을 나열하지 않습니다. 그것들의 목록을 원한다면, 표준 모듈 <code>builtins</code> 에 정의되어 있습니다<syntaxhighlight lang="py3">>>> 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']</syntaxhighlight> ==== 패키지 ====https://docs.python.org/ko/3.8/tutorial/modules.html#packages 패키지는 “점으로 구분된 모듈 이름” 를 써서 파이썬의 모듈 이름 공간을 구조화하는 방법입니다. 예를 들어, 모듈 이름 <code>A.B</code> 는 <code>A</code> 라는 이름의 패키지에 있는 <code>B</code> 라는 이름의 서브 모듈을 가리킵니다. 모듈의 사용이 다른 모듈의 저자들이 서로의 전역 변수 이름들을 걱정할 필요 없게 만드는 것과 마찬가지다. 음향 파일과 과 음향 데이터의 일관된 처리를 위한 모듈들의 컬렉션 (“패키지”) 을 설계하길 원한다고 합시다.<syntaxhighlight>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 ...</syntaxhighlight>패키지를 임포트할 때, 파이썬은 <code>sys.path</code> 에 있는 디렉터리들을 검색하면서 패키지 서브 디렉터리를 찾습니다. 파이썬이 디렉터리를 패키지로 취급하게 만들기 위해서 <code>__init__.py</code> 파일이 필요합니다. <code>__init__.py</code> 는 그냥 빈 파일일 수 있지만, 패키지의 초기화 코드를 실행하거나 뒤에서 설명하는 <code>__all__</code> 변수를 설정할 수 있습니다. 패키지 사용자는 패키지로부터 개별 모듈을 임포트할 수 있습니다, 예를 들어<syntaxhighlight lang="py3">import sound.effects.echo</syntaxhighlight>다음처럼 전체 이름으로 참조되어야 합니다.<syntaxhighlight lang="py3">sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)</syntaxhighlight>다른 방법으로<syntaxhighlight lang="py3">from sound.effects import echo</syntaxhighlight>이제 간단하게 다음처럼 사용할 수 있다.<syntaxhighlight lang="py3">echo.echofilter(input, output, delay=0.7, atten=4)</syntaxhighlight>또 다른 방법은 원하는 함수나 변수를 직접 임포트 할 수도 있다.<syntaxhighlight lang="py3">from sound.effects.echo import echofilter</syntaxhighlight>함수를 직접 사용할 수 있게 만들어 준다.<syntaxhighlight lang="py3">echofilter(input, output, delay=0.7, atten=4)</syntaxhighlight> == 설정 및 사용법 ==출처: 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'' 는 개행 문자로 구분된 하나 이상의 문장일 수 있다.  이 옵션을 주면, <code>sys.argv</code> 의 첫 번째 요소는 <code>"-c"</code> 가 되고, 현재 디렉터리를 <code>sys.path</code> 의 시작 부분에 추가합니다 ====== -m <module-name> ======제공된 이름의 모듈을 <code>sys.path</code> 에서 검색하고 그 내용을 <code>__main__</code> 모듈로서 실행합니다. 인자가 ''모듈'' 이름이기 때문에, 파일 확장자(<code>.py</code>)를 주지 않아야 합니다.  패키지 이름(이름 공간 패키지 포함)도 허용됩니다. 일반 모듈 대신 패키지 이름이 제공되면, 인터프리터는 <code><pkg>.__main__</code> 을 메인 모듈로 실행합니다.  이 옵션을 주면, <code>sys.argv</code> 의 첫 번째 요소는 모듈 파일의 전체 경로가 됩니다. ====== <script> ======''script'' 는 파이썬 파일이나 <code>__main__.py</code> 파일이 들어있는 디렉터리나 <code>__main__.py</code> 파일을 포함하는 zip 파일을 가리키는 파일 시스템 경로(절대나 상대)여야 합니다. ==== 환경변수 ==== ===== PYTHONHOME =====표준 파이썬 라이브러리의 위치를 변경합니다. 기본값은 <code>/usr/local</code> 입니다. ===== PYTHONPATH =====모듈 파일의 기본 검색 경로를 보강합니다. 유닉스에서는 콜론, 윈도우에서는 세미콜론. ==웹 크롤링==[[Selenium]] == string == === split ===https://www.w3schools.com/python/ref_string_split.asp=== trim===https://www.w3schools.com/python/ref_string_strip.asp ===[[Python#len|length]]=== === substring ===문자열은 배열과 같으므로 다음과 같이 접근이 가능하다.  -는 negative index로 뒤에서 5번째에서 뒤에서 세번째까지의 문자열을 구할 수도 있다.<syntaxhighlight lang="python">string[2:5] string[-5:-3]</syntaxhighlight> ==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
==에러==
에러메시지: TypeError=== UnicodeDecodeError: 'NoneTypeascii' codec can't decode byte===import sys 이후에 다음 코드 추가 reload(sys) sys.setdefaultencoding('utf-8' object is not callable)
/usr/lib/python3.5/weakref.py 파일수정해야한다.== 외부링크 ==
공백과 탭은 구분되므로 공백으로 맞추어 수정해야 한다=== 문서 ===https://docs.python.org/ko/3/
다음을 def remove(wr, selfref=ref(self)):다음으로 수정한다. def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref)= lexical analyzer ====https://docs.python.org/ko/3/reference/lexical_analysis.html
다음을 ===== 리터럴 ===== _remove_dead_weakref(d, wrhttps://docs.key)다음으로 수정한다python.org/ko/3/reference/lexical_analysis.html#literals _atomic_removal(d, wr.key)[[분류:프로그래밍]]
편집
2,431