Hodustory/프로그래밍&DB

파이썬(python) 입문 : 기본 모듈, dir()함수

호두밥 2018. 3. 29. 23:59

기본 모듈(Standard Modules)


파이썬은 표준 모듈 라이브러리를 제공합니다. 일부 모듈은 인터프리터에 내장되어 있습니다. 이것들은 시스템 호출 같은 운영 체제의 기본 요소에 대한 접근을 제공하거나 효율성을 제공합니다. 이런 모듈 세트는 기본 플랫폼에 의존하는 구성 옵션입니다. winreg 모듈은 윈도우 시스템에서만 제공됩니다. 

모든 파이썬 인터프리터에 내장된 sys 모듈은 주의가 필요합니다. 변수 sys.ps1과 sys.ps2는 첫번째와 두번째 프롬프트에서 쓰이는 문자열을 정의합니다.


>>> import sys

>>> sys.ps1

'>>> '

>>> sys.ps2

'... '


이 두개의 변수는 오직 활동중인 인터프리터에서만 작동합니다.

변수 sys.path는 모듈을 위한 인터프리터의 검색 패스를 결정하는 문자열의 리스트입니다. 이것은 환경변수 PYTHONPATH나 PYTHONPATH가 없으면 내장된 고정값에서 지정된 고정 패스로 초기화됩니다. 기본 리스트 함수를 사용해 그것을 바꿀 수 있습니다.


>>> sys.path

['', 'C:\\Python\\python36.zip', 'C:\\Python\\DLLs', 'C:\\Python\\lib', 'C:\\Python', 'C:\\Python\\lib\\site-packages']

>>> sys.path.append('/name/bin/python')


dir() 함수 (dir() Funtion)


내장함수 dir()은 정의된 모듈의 이름을 찾을 때 사용합니다. 값은 문자열 리스트로 반환합니다.


>>> dir(sys)

['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache',

 '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_m

odule_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'fl

ags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfi

lesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_

info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', '

prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',

 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']


인수 없이 dir()을 쓰면 현재 정의한 것들의 이름을 반환합니다. 이 때 반환된 리스트는 변수, 모듈, 함수 등 모든 것의 이름이 포함됩니다.


>>> dir()

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

>>> a=['a']

>>> dir()

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']


dir()은 내장 함수와 변수의 이름으로 구성된 리스트가 아닙니다. 이것들로 리스트를 만들려면, 기본 모듈 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', 'FileNo
tFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError'
, 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'Ov
erflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIte
ration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'Unicod
eEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__'
, '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'comp
ile', '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', 'z
ip']


-----------------------------------

안녕하세요. 호두입니다.

이번엔 기본 모듈과 dir()함수를 배웠네요.

기본 모듈에 어떤 것들이 있는 지는 뒤에 따로 나올까요? 간단한 소개 정도에만 그치고 있네요.

dir()은 종종 유용하게 쓰일 듯 합니다. 현재 파일에서 정의된 모든 것들을 확인할 수 있는 기능이니까요.


반응형