Skip to content

Instantly share code, notes, and snippets.

@davidhcefx
Last active August 5, 2023 17:37
Show Gist options
  • Save davidhcefx/20f9ebaa879d33b4707c3ad9b07f75ad to your computer and use it in GitHub Desktop.
Save davidhcefx/20f9ebaa879d33b4707c3ad9b07f75ad to your computer and use it in GitHub Desktop.
defining ipython custom magic command

help - IPython Custom Magic Command

If you are a command-line lover, then it is likely that ipython is already one of your friend. In Python, help() is our swiss army knife. However, always having to embrace commands with parathesis, ( and ), is really a hassle! Wouldn't it be great if we could simply invoke like this?

%help unknown_command

Instructions

  1. Create a file ipython_startup.py with the following content:
from IPython.core.magic import register_line_magic

@register_line_magic
def help(line):
    if line == '':
        help()
    else:
        help(eval(line))

del help
  1. Set c.InteractiveShellApp.exec_files = ['/path/to/your/file'] within your ipython_config.py.

References:

hex - IPython Custom Magic Command

Tired of converting numbers with hex() each and every time? For example:

>>> (0x4cef9 << 3) + 0x9a8826
12648430   # <-- WHAT IS THIS???

So, this tool comes to the rescure!

Features

>>> %hex (0x12345 >> 4) ^ 0xfffff
'0xfedcb'

>>> %hex np.array([0xdead, 0xbeef]) ^ 0x42
['0xdeef', '0xbead']

>>> %hex [[random.randint(0, 0xffff) for j in range(3)] for i in range(2)]
[['0x32c1', '0xef67', '0xb3c3'], ['0xf953', '0x712b', '0x3002']]

Instructions

  1. Create a file ipython_startup.py with the following content:
from IPython.core.magic import register_line_magic

@register_line_magic
def hex(line):
    return _hex_helper(eval(line))

def _hex_helper(number):
    if hasattr(number, '__iter__'):
        return [_hex_helper(num) for num in number]
    else:
        return hex(number)

del hex
  1. Set c.InteractiveShellApp.exec_files = ['/path/to/your/file'] within your ipython_config.py.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment