.py
확장자를 가진 파일을 하나 만들고 그 안에 함수들과 변수들을 정의해 두는 것입니다.module_using_sys.py
로 저장하세요):sys
모듈을 import
문을 통해 불러왔습니다. 이것은 단순히 파이썬에게 이 모듈을 앞으로 사용할 것이라고 알려주는 과정이라고 생각하시면 편합니다. 여기서 사용된 sys
모듈은 파이썬 인터프리터와 인터프리터가 실행중인 환경, 즉 시스템(system)에 관련된 기능들이 담겨 있습니다.import sys
문을 실행하는 시점에서, 파이썬은 sys
모듈을 찾습니다. 이 경우에는 내장 모듈을 불러오는 것이므로, 파이썬이 이미 어디서 이것을 불러와야 하는지 알고 있습니다.sys.path
변수 에 정의된 디렉토리들에 해당 모듈이 있는지 검색합니다. 그리고 나서 모듈을 찾아내면, 그 모듈 내부에 적혀있는 명령들이 읽어들여지게 되며 그 다음부터 모듈이 사용가능하게 됩니다. 이러한 초기화 과정은 첫번째로 모듈을 불러올 때만 이루어진다는 것을 기억하세요.sys
모듈의 argv
변수를 불러올 때, 마침표를 이용하여 sys.argv
와 같이 접근합니다. 이와 같이 마침표를 이용함으로써 뒤에 온 이름이 sys
모듈에 존재한다는 것을 명시적으로 알려 주고, 또한 여러분의 프로그램에 사용될지 모를 argv
라는 이름을 가진 다른 변수와 충돌이 일어나지 않도록 합니다.sys.argv
변수는 문자열의 리스트 입니다 (리스트에 대해서는 다음 장)에서 좀 더 자세히 다룰 것입니다). 좀 더 구체적으로 sys.argv
가 담고 있는 것은 명령줄 인수들의 리스트인데, 이것은 명령줄로부터 프로그램을 실행시킬 때 함께 넘어온 인수들을 담고 있는 것입니다.python module_using_sys.py we are arguments
명령을 통해 실행하였습니다. 이것은 python
명령을 통해 module_using_sys.py
모듈을 실행시키고 함께 적어준 명령줄 인수들을 실행될 프로그램에 넘겨준 것입니다. 그러면 파이썬은 sys.argv
변수에 이것을 저장해 주며 프로그램에서 사용할 수 있도록 합니다.sys.argv
리스트의 첫번째 항목이 됨을 기억하세요. 즉, 이 경우 'module_using_sys.py'
가 sys.argv[0]
에 해당하며, 'we'
는 sys.argv[1]
에, 'are'
는 sys.argv[2]
에, 'arguments'
는 sys.argv[3]
에 해당합니다. 파이선은 숫자를 0부터 센다는 점을 기억하세요 (1이 아닙니다!).sys.path
변수에는 모듈을 불러올 때 찾게 되는 디렉토리들의 리스트가 담겨 있습니다. sys.path
변수의 첫 번째 항목이 공백 문자열임을 확인하세요. 공백 문자열은 현재 디렉토리를 의미하는데, 따라서 이것은 현재 디렉토리 또한 sys.path
의 일부임을 의미하며 이것은 PYTHONPATH
환경변수의 경우와도 같습니다. 즉, 여러분은 현재 디렉토리에 들어 있는 파이썬 모듈을 불러와 사용할 수 있는 것입니다. 그렇지 않은 경우, sys.path
에 지정된 디렉토리들 중 하나에 해당 모듈이 들어 있어야 합니다.import os; print(os.getcwd())
를 실행하여 여러분의 프로그램에서 현재 디렉토리가 어디인지 확인할 수 있습니다..pyc
확장자를 가진 바이트 컴파일 이라고 부르는 전처리를 한번 거친 중간 파일들로 변환해 두어 미리 저장해 두었다가 사용하는 것입니다 (파이썬이 어떻게 동작하는지 서문에서 언급했던 것을 기억하나요?). 이러한 .pyc
파일들은 해당 모듈이 다른 프로그램에서 또다시 사용될 때 모듈의 소스 코드 대신 불러들여지게 되는데, 이 때 이 파일들은 이미 전처리를 한번 거친 파일들이므로 모듈을 매번 불러오는 것 보다 훨씬 빠르게 해당 모듈을 불러올 수 있습니다. 이러한 바이트 컴파일 된 파일들은 플랫폼 독립적입니다 (즉, 다른 시스템에서도 수정 없이 사용될 수 있습니다)..pyc
파일들은 해당 .py
파일들과 같은 디렉토리에 생성됩니다. 만약 해당 디렉토리가 읽기 전용으로 설정되어 있으면, .pyc
파일들은 생성되지 않습니다.sys.argv
라고 작성하는 대신에, 짧게 argv
변수를 프로그램 안에서 직접 사용하고 싶다고 합시다 (즉, 매번 argv
앞에 sys.
를 붙이지 않아도 되게끔요). 이 때 from syst import argv
문을 사용할 수 습니다.경고: 일반적인 상황에서 가능하면from..import
문을 사용하지 말고,import
문을 대신 활용하세요. 이렇게 하는 편이 이름 간의 충돌을 막는데도 유용하거니와, 프로그램을 좀 더 읽기 쉽게도 해 줍니다.
__name__
__name__
속성을 활용할 수 있습니다.module_using_name.py
으로 저장하세요):__name__
속성을 정의하고 있습니다. 만약 이것이 '__main__'
이라는 문자열이라면 모듈이 독립적으로 실행중이라는 것을 의미하며, 그에 따른 적절한 처리를 할 수 있습니다..py
여야 한다는 점 뿐입니다. 다음 예제를 통해 모듈을 만드는 법에 대해 좀 더 확실히 이해해 봅시다.mymodule.py
로 저장하세요):sys.path
.mymodule_demo.py
):from..import
syntax (save as mymodule_demo2.py
):mymodule_demo2.py
is same as the output of mymodule_demo.py
.__version__
name declared in the module that imports mymodule, there would be a clash. This is also likely because it is common practice for each module to declare it's version number using this name. Hence, it is always recommended to prefer the import
statement even though it might make your program a little longer.say_hi
but would not import __version__
because it starts with double underscores.WARNING: Remember that you should avoid using import-star, i.e.from mymodule import *
.
Zen of PythonOne of Python's guiding principles is that "Explicit is better than Implicit". Runimport this
in Python to learn more.
dir
functiondir()
function returns the list of names defined by an object. If the object is a module, this list includes functions, classes and variables, defined inside that module.dir
on the imported sys
module. We can see the huge list of attributes that it contains.dir
function without passing parameters to it. By default, it returns the list of attributes for the current module. Notice that the list of imported modules is also part of this list.dir
in action, we define a new variable a
and assign it a value and then check dir
and we observe that there is an additional value in the list of the same name. We remove the variable/attribute of the current module using the del
statement and the change is reflected again in the output of the dir
function.del
: This statement is used to delete a variable/name and after the statement has run, in this case del a
, you can no longer access the variable a
- it is as if it never existed before at all.dir()
function works on any object. For example, run dir(str)
for the attributes of the str
(string) class.vars()
function which can potentially give you the attributes and their values, but it will not work for all cases.__init__.py
file that indicates to Python that this folder is special because it contains Python modules.