주 메뉴 열기

wwiki β

바뀜

Python

5,504 바이트 추가됨, 2023년 1월 20일 (금) 10:24
모듈 검색 경로
* 설치 의존적인 기본값
==== dir() 함수 ====
모듈이 정의하는 이름들을 찾는다. 문자열 리스트를 반환한다.
 
인자가 없으면, <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>
 
==== 패키지 ====
패키지는 “점으로 구분된 모듈 이름” 를 써서 파이썬의 모듈 이름 공간을 구조화하는 방법입니다. 예를 들어, 모듈 이름 <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><br />
==웹 크롤링==
[[Selenium]]
편집
2,431