python_reference/ipython_magic/datemagic.py

89 lines
2.8 KiB
Python
Raw Normal View History

2014-06-28 05:16:59 +00:00
__version__ == '1.0.0'
2014-06-28 04:46:45 +00:00
"""
IPython magic function for printing basic information, such as the current date, time,
Python, and IPython version.
Installation:
%install_ext https://raw.githubusercontent.com/rasbt/python_reference/master/ipython_magic/datemagic.py
Usage:
%load_ext datemagic
%date
optional arguments:
-d, --date prints date (default)
-t, --time print current time
-s, --datetime print current time
-p, --python prints Python version
-i, --ipython prints IPython version
"""
import platform
from time import strftime
from platform import python_version
2014-06-28 05:16:59 +00:00
from pkg_resources import get_distribution
2014-06-28 04:46:45 +00:00
import IPython
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
@magics_class
class DateMagic(Magics):
"""
IPython magic function for printing the current date, time, Python,
and IPython version.
"""
@magic_arguments()
@argument('-d', '--date', action='store_true', help='prints date (default)')
2014-06-28 05:16:59 +00:00
@argument('-dd', '--dateday', action='store_true', help='prints date with abbrv. day and month names')
2014-06-28 04:46:45 +00:00
@argument('-t', '--time', action='store_true', help='print current time')
@argument('-s', '--datetime', action='store_true', help='print current time')
2014-06-28 05:16:59 +00:00
@argument('-z', '--timezone', action='store_true', help='prints time zone')
@argument('-y', '--python', action='store_true', help='prints Python version')
2014-06-28 04:46:45 +00:00
@argument('-i', '--ipython', action='store_true', help='prints IPython version')
2014-06-28 05:16:59 +00:00
@argument('-p', '--packages', action=str, help='prints versions of Python modules and packages')
2014-06-28 04:46:45 +00:00
@line_magic
def date(self, line):
"""
IPython magic function for printing the current date, time, Python,
and IPython version.
"""
args = parse_argstring(self.date, line)
out = ''
if args.date:
out += strftime('%d/%m/%Y')
2014-06-28 05:16:59 +00:00
elif arts.dateday:
out += strftime('%a %b %M %Y')
2014-06-28 04:46:45 +00:00
if args.time:
if out:
out += ' '
out += strftime('%H:%M:%S')
2014-06-28 05:16:59 +00:00
if args.timezone:
if out:
out += ' '
out += strftime('%Z')
2014-06-28 04:46:45 +00:00
if args.python:
if out:
out += '\n'
out += 'Python %s' %python_version()
if args.ipython:
if out:
out += '\n'
out += 'IPython %s' %IPython.__version__
2014-06-28 05:16:59 +00:00
if args.packages:
packages = args.packages.split(',')
for p in packages:
out += '\n%s' %get_distribution(p).version
2014-06-28 04:46:45 +00:00
if not out:
out += strftime('%d/%m/%Y')
print(out)
def load_ipython_extension(ipython):
ipython.register_magics(DateMagic)