파이썬 기초 강좌 #5 IPython

7 분 소요

오늘의 강좌에서는 IPython 쉘에 대해서 알아 보도록 하겠습니다.

파이썬 공부를 하시거나 코딩을 하실 때, 간단한 코드 테스트를 하기 위해서 파이썬 쉘을 자주 사용하게 됩니다. 파이썬 쉘이란 파이썬 인터프레터를 인터엑티브 모드로 사용할 수 있는 어플리케이션입니다. 윈도우의 커맨드나 맥OS, 리눅스의 터미널을 사용하는 것과 비슷하다고 생각하시면 됩니다. 자바스크립트로 개발을 해 본 분이라면 자바스크립트 콘솔과 같다고 보시면 됩니다. 아나콘다 파이썬을 설치 하셨다면 Ipython이 이미 설치 되어 있을겁니다. 만약 일반 파이썬을 설치 하셨다면 다음 명령어를 통해서 간단히 설치를 하실 수 있습니다.

pip install ipython 혹시 아나콘다 파이썬을 설치하고 싶으시다면 파이썬 기초강좌 #2 파이썬 설치하기를 시청하시기 바랍니다.

그럼 Ipython 쉘의 사용 방법을 알아 보도록 하겠습니다. 먼저 파이썬의 기본 쉘을 보여 드린 후에 IPython 쉘을 보여드리도록 하겠습니다.

커맨드를 실행하신 후 python이라고 입력합니다. 맥OS나 리눅스를 사용하신다면 터미널에서 실행하시면 됩니다.

OS에 설치 되어있는 파이썬 버전이 출력되면서 파이썬 쉘이 실행되었습니다.

Hello World 문자열을 출력하는 코드를 입력해 보겠습니다.

>>> print('Hello World!')
Hello World!

변수를 정의하고 변수에 저장된 값을 출력해 보겠습니다.

>>> myvar = 'This is myvar variable'
>>> print(myvar)
This is myvar variable

파이썬 라이브러리에서 OS모듈을 임포트하여 현재 폴더 위치를 출력해 보겠습니다.

>>> import os
>>> os.getcwd()
'C:\\\\Users\\\\Curtis'
이번에는 for 문을 사용하여 보도록 하겠습니다.
 
>>> for i in range(10):
...   print(i)
...
0
1
2
3
4
5
6
7
8
9

이렇게 파이썬 쉘을 사용하시면 간단한 코드를 소스 파일에 저장하여 실행할 필요 없이 간단히 실행하실 수가 있습니다.

이번에는 일반 파이썬 쉘과 Ipython의 차이점에 대해서 알아보도록 하겠습니다.

커맨드창에서 ipython을 입력합니다. ipython 쉘이 실행되었습니다. 조금 전에 일반 파이썬 쉘에서 실행한 코드를 실행해 보도록 하겠습니다.

In [1]: print('Hello World!')
Hello World!

일반 파이썬 쉘과는 달리 코드의 가독성을 높여주는 코드 하이라이팅 기능을 제공합니다.

일반 파이썬 쉘에서는 제공하지 않은 편리한 탭 컴플리션 기능을 제공합니다.

In [2]: myvar = 'This is myvar variable'
In [3]: print(myvar)
This is myvar variable

모듈에 포함되어 있는 모든 함수들을 볼 수도 있습니다.

In [4]: import os
In [5]: os.getcwd()
Out[5]: 'D:\\\\OneDrive\\\\Projects\\\\Python Tutorials\\\\tutorial 5'

물음표를 사용해 모듈에 대한 설명이나 함수 또는 메소드에 대한 설명을 참조할 수도 있습니다.

In [6]: os?
Type:        module
String form: <module 'os' from 'C:\\\\Users\\\\CURTIS\\\\anaconda3\\\\lib\\\\os.py'>
File:        c:\\users\\curtis\\anaconda3\\lib\\os.py
Docstring:
OS routines for NT or Posix depending on what system we're on.
 
This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\\r' or '\\n' or '\\r\\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
 
Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
 
In [7]: os.getcwd?
Signature: os.getcwd()
Docstring: Return a unicode string representing the current working directory.
Type:      builtin_function_or_method

마지막으로 IPython이 제공하는 매직 함수 중에서 몇가지를 살펴 보고 이번 강좌를 마치도록 하겠습니다. 매직 함수를 사용하면 파이썬 모듈을 임포트하여야 할 수 있는 것들을 간단히 해결 할 수 있습니다. 먼저 현재 폴더의 파일을 리스팅해 보겠습니다. 이번에는 test라는 새로운 폴더를 만들고 test 폴더로 이동해 보겠습니다. 이 밖에도 정말 펀리한 매직 함수를 많이 제공하고 있는데 매직함수의 리스트는 다음의 명령어로 출력할 수 있습니다.

In [18]: %quickref
 
IPython -- An enhanced Interactive Python - Quick Reference Card
================================================================
 
obj?, obj??      : Get help, or more help for object (also works as
?obj, ??obj).
?foo.*abc*       : List names in 'foo' containing 'abc' in them.
%magic           : Information about IPython's 'magic' % functions.
 
Magic functions are prefixed by % or %%, and typically take their arguments
without parentheses, quotes or even commas for convenience.  Line magics take a
single % and cell magics are prefixed with two %%.
 
Example magic function calls:
 
%alias d ls -F   : 'd' is now an alias for 'ls -F'
alias d ls -F    : Works if 'alias' not a python name
alist = %alias   : Get list of aliases to 'alist'
cd /usr/share    : Obvious. cd -<tab> to choose from visited dirs.
%cd??            : See help AND source for magic %cd
%timeit x=10     : time the 'x=10' statement with high precision.
%%timeit x=2**100
x**100           : time 'x**100' with a setup of 'x=2**100'; setup code is not
counted.  This is an example of a cell magic.
 
System commands:
 
!cp a.txt b/     : System command escape, calls os.system()
cp a.txt b/      : after %rehashx, most system commands work without !
---Return to continue, q to quit---

앞에서도 말씀 드렸듯이 파이썬 쉘은 개발을 할 때 코드 테스트나 모듈 테스트 등에 많이 쓰이며, 공부를 하면서도 간단히 코드를 테스트 할 수 있는 편리한 툴이므로 꼭 익숙해지시기 바랍니다. 여기서 이번 강좌를 마치고 다음 강좌에서는 Jupyter Notebook에 대해서 알아보도록 하겠습니다.