over/core/misc.py
Overwatch 402a05f86d - over.core.misc.console now accepts globals as well as locals to offer a complete environment
- new over.core.file.count_lines
- over.core.types.ndict can now export keys with dashes in them same way over.core.app.Main does it (by translating them to underscores)
2015-01-14 13:14:34 +01:00

73 lines
1.5 KiB
Python

#! /bin/env python3
# encoding: utf-8
import copy
import imp
import os
# --------------------------------------------------
def import_module(path):
'''
Imports a python file as a module. The path can be relative or absolute.
Based on the work of Yuval Greenfield released into the public domain.
'''
# remove the .py suffix
mod_dn = os.path.dirname(path)
mod_fn = os.path.basename(path)
if mod_fn.endswith('.py'):
mod_name = mod_fn[:-3]
else:
# packages for example
mod_name = mod_fn
fd = None
try:
data = imp.find_module(mod_name, [mod_dn])
module = imp.load_module(mod_name, *data)
fd = data[0]
finally:
if fd is not None:
fd.close()
return module
# --------------------------------------------------
def batch_gen(data, batch_size):
'''
Split data (a sequence) into sequences batch_size elements long.
'''
for i in range(0, len(data), batch_size):
yield data[i:i+batch_size]
# --------------------------------------------------
def console(locals, globals=None, tab_completion=False):
'''
Opens up a Python console.
tab_completion enables completion of object names using TAB, however note
that this will make pasting formatted snippets of code difficult
'''
import code, readline, rlcompleter
environment = copy.copy(locals)
if globals:
for key, value in globals.items():
if key not in environment:
environment[key] = value
if tab_completion:
readline.parse_and_bind('tab: complete')
c = code.InteractiveConsole(environment)
c.interact(banner='')