From 83a5d322d248bf8a12dc1c1b1b83387a321cb217 2013-07-19 00:35:02 From: MinRK Date: 2013-07-19 00:35:02 Subject: [PATCH] remove quarantine it's been long enough, and these files can always be found in the git history --- diff --git a/IPython/quarantine/InterpreterExec.py b/IPython/quarantine/InterpreterExec.py deleted file mode 100644 index 8d1a2a3..0000000 --- a/IPython/quarantine/InterpreterExec.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -"""Modified input prompt for executing files. - -We define a special input line filter to allow typing lines which begin with -'~', '/' or '.'. If one of those strings is encountered, it is automatically -executed. -""" - -#***************************************************************************** -# Copyright (C) 2004 W.J. van der Laan -# Copyright (C) 2004-2006 Fernando Perez -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - - -def prefilter_shell(self,line,continuation): - """Alternate prefilter, modified for shell-like functionality. - - - Execute all lines beginning with '~', '/' or '.' - - $var=cmd <=> %sc var=cmd - - $$var=cmd <=> %sc -l var=cmd - """ - - if line: - l0 = line[0] - if l0 in '~/.': - return self._prefilter("!%s"%line,continuation) - elif l0=='$': - lrest = line[1:] - if lrest.startswith('$'): - # $$var=cmd <=> %sc -l var=cmd - return self._prefilter("%ssc -l %s" % (self.ESC_MAGIC,lrest[1:]), - continuation) - else: - # $var=cmd <=> %sc var=cmd - return self._prefilter("%ssc %s" % (self.ESC_MAGIC,lrest), - continuation) - else: - return self._prefilter(line,continuation) - else: - return self._prefilter(line,continuation) - -# Rebind this to be the new IPython prefilter: -from IPython.core.iplib import InteractiveShell -InteractiveShell.prefilter = prefilter_shell -# Clean up the namespace. -del InteractiveShell,prefilter_shell - -# Provide pysh and further shell-oriented services -import os,sys,shutil -from IPython.utils.process import system,shell,getoutput,getoutputerror - -# Short aliases for getting shell output as a string and a list -sout = getoutput -lout = lambda cmd: getoutput(cmd,split=1) - -# Empty function, meant as a docstring holder so help(pysh) works. -def pysh(): - """Pysh is a set of modules and extensions to IPython which make shell-like - usage with Python syntax more convenient. Keep in mind that pysh is NOT a - full-blown shell, so don't try to make it your /etc/passwd entry! - - In particular, it has no job control, so if you type Ctrl-Z (under Unix), - you'll suspend pysh itself, not the process you just started. - - Since pysh is really nothing but a customized IPython, you should - familiarize yourself with IPython's features. This brief help mainly - documents areas in which pysh differs from the normal IPython. - - ALIASES - ------- - All of your $PATH has been loaded as IPython aliases, so you should be - able to type any normal system command and have it executed. See %alias? - and %unalias? for details on the alias facilities. - - SPECIAL SYNTAX - -------------- - Any lines which begin with '~', '/' and '.' will be executed as shell - commands instead of as Python code. The special escapes below are also - recognized. !cmd is valid in single or multi-line input, all others are - only valid in single-line input: - - !cmd - pass 'cmd' directly to the shell - !!cmd - execute 'cmd' and return output as a list (split on '\\n') - $var=cmd - capture output of cmd into var, as a string - $$var=cmd - capture output of cmd into var, as a list (split on '\\n') - - The $/$$ syntaxes make Python variables from system output, which you can - later use for further scripting. The converse is also possible: when - executing an alias or calling to the system via !/!!, you can expand any - python variable or expression by prepending it with $. Full details of - the allowed syntax can be found in Python's PEP 215. - - A few brief examples will illustrate these: - - fperez[~/test]|3> !ls *s.py - scopes.py strings.py - - ls is an internal alias, so there's no need to use !: - fperez[~/test]|4> ls *s.py - scopes.py* strings.py - - !!ls will return the output into a Python variable: - fperez[~/test]|5> !!ls *s.py - <5> ['scopes.py', 'strings.py'] - fperez[~/test]|6> print _5 - ['scopes.py', 'strings.py'] - - $ and $$ allow direct capture to named variables: - fperez[~/test]|7> $astr = ls *s.py - fperez[~/test]|8> astr - <8> 'scopes.py\\nstrings.py' - - fperez[~/test]|9> $$alist = ls *s.py - fperez[~/test]|10> alist - <10> ['scopes.py', 'strings.py'] - - alist is now a normal python list you can loop over. Using $ will expand - back the python values when alias calls are made: - fperez[~/test]|11> for f in alist: - |..> print 'file',f, - |..> wc -l $f - |..> - file scopes.py 13 scopes.py - file strings.py 4 strings.py - - Note that you may need to protect your variables with braces if you want - to append strings to their names. To copy all files in alist to .bak - extensions, you must use: - fperez[~/test]|12> for f in alist: - |..> cp $f ${f}.bak - - If you try using $f.bak, you'll get an AttributeError exception saying - that your string object doesn't have a .bak attribute. This is because - the $ expansion mechanism allows you to expand full Python expressions: - fperez[~/test]|13> echo "sys.platform is: $sys.platform" - sys.platform is: linux2 - - IPython's input history handling is still active, which allows you to - rerun a single block of multi-line input by simply using exec: - fperez[~/test]|14> $$alist = ls *.eps - fperez[~/test]|15> exec _i11 - file image2.eps 921 image2.eps - file image.eps 921 image.eps - - While these are new special-case syntaxes, they are designed to allow very - efficient use of the shell with minimal typing. At an interactive shell - prompt, conciseness of expression wins over readability. - - USEFUL FUNCTIONS AND MODULES - ---------------------------- - The os, sys and shutil modules from the Python standard library are - automatically loaded. Some additional functions, useful for shell usage, - are listed below. You can request more help about them with '?'. - - shell - execute a command in the underlying system shell - system - like shell(), but return the exit status of the command - sout - capture the output of a command as a string - lout - capture the output of a command as a list (split on '\\n') - getoutputerror - capture (output,error) of a shell command - - sout/lout are the functional equivalents of $/$$. They are provided to - allow you to capture system output in the middle of true python code, - function definitions, etc (where $ and $$ are invalid). - - DIRECTORY MANAGEMENT - -------------------- - Since each command passed by pysh to the underlying system is executed in - a subshell which exits immediately, you can NOT use !cd to navigate the - filesystem. - - Pysh provides its own builtin '%cd' magic command to move in the - filesystem (the % is not required with automagic on). It also maintains a - list of visited directories (use %dhist to see it) and allows direct - switching to any of them. Type 'cd?' for more details. - - %pushd, %popd and %dirs are provided for directory stack handling. - - PROMPT CUSTOMIZATION - -------------------- - - The supplied ipythonrc-pysh profile comes with an example of a very - colored and detailed prompt, mainly to serve as an illustration. The - valid escape sequences, besides color names, are: - - \\# - Prompt number. - \\D - Dots, as many as there are digits in \\# (so they align). - \\w - Current working directory (cwd). - \\W - Basename of current working directory. - \\XN - Where N=0..5. N terms of the cwd, with $HOME written as ~. - \\YN - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown. - \\u - Username. - \\H - Full hostname. - \\h - Hostname up to first '.' - \\$ - Root symbol ($ or #). - \\t - Current time, in H:M:S format. - \\v - IPython release version. - \\n - Newline. - \\r - Carriage return. - \\\\ - An explicitly escaped '\\'. - - You can configure your prompt colors using any ANSI color escape. Each - color escape sets the color for any subsequent text, until another escape - comes in and changes things. The valid color escapes are: - - \\C_Black - \\C_Blue - \\C_Brown - \\C_Cyan - \\C_DarkGray - \\C_Green - \\C_LightBlue - \\C_LightCyan - \\C_LightGray - \\C_LightGreen - \\C_LightPurple - \\C_LightRed - \\C_Purple - \\C_Red - \\C_White - \\C_Yellow - \\C_Normal - Stop coloring, defaults to your terminal settings. - """ - pass - -# Configure a few things. Much of this is fairly hackish, since IPython -# doesn't really expose a clean API for it. Be careful if you start making -# many modifications here. - - -# Set the 'cd' command to quiet mode, a more shell-like behavior -__IPYTHON__.default_option('cd','-q') - -# This is redundant, ipy_user_conf.py will determine this -# Load all of $PATH as aliases -__IPYTHON__.magic_rehashx() - -# Remove %sc,%sx if present as aliases -__IPYTHON__.magic_unalias('sc') -__IPYTHON__.magic_unalias('sx') - -# We need different criteria for line-splitting, so that aliases such as -# 'gnome-terminal' are interpreted as a single alias instead of variable -# 'gnome' minus variable 'terminal'. -import re -__IPYTHON__.line_split = re.compile(r'^([\s*,;/])' - r'([\?\w\.\-\+]+\w*\s*)' - r'(\(?.*$)') - -# Namespace cleanup -del re diff --git a/IPython/quarantine/__init__.py b/IPython/quarantine/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/quarantine/__init__.py +++ /dev/null diff --git a/IPython/quarantine/envpersist.py b/IPython/quarantine/envpersist.py deleted file mode 100644 index 45d68fd..0000000 --- a/IPython/quarantine/envpersist.py +++ /dev/null @@ -1,92 +0,0 @@ -# -*- coding: utf-8 -*- -""" %env magic command for storing environment variables persistently -""" - -from IPython.core import ipapi -from IPython.core.error import TryNext - -ip = ipapi.get() - -import os,sys - -def restore_env(self): - ip = self.getapi() - env = ip.db.get('stored_env', {'set' : {}, 'add' : [], 'pre' : []}) - for k,v in env['set'].items(): - os.environ[k] = v - for k,v in env['add']: - os.environ[k] = os.environ.get(k,"") + v - for k,v in env['pre']: - os.environ[k] = v + os.environ.get(k,"") - raise TryNext - -ip.set_hook('late_startup_hook', restore_env) - -def persist_env(self, parameter_s=''): - """ Store environment variables persistently - - IPython remembers the values across sessions, which is handy to avoid - editing startup files. - - %env - Show all environment variables - %env VISUAL=jed - set VISUAL to jed - %env PATH+=;/foo - append ;foo to PATH - %env PATH+=;/bar - also append ;bar to PATH - %env PATH-=/wbin; - prepend /wbin; to PATH - %env -d VISUAL - forget VISUAL persistent val - %env -p - print all persistent env modifications - """ - - if not parameter_s.strip(): - return os.environ.data - - ip = self.getapi() - db = ip.db - env = ip.db.get('stored_env', {'set' : {}, 'add' : [], 'pre' : []}) - - if parameter_s.startswith('-p'): - return env - - elif parameter_s.startswith('-d'): - parts = (parameter_s.split()[1], '') - - else: - parts = parameter_s.strip().split('=') - - if len(parts) == 2: - k,v = [p.strip() for p in parts] - - if v == '': - if k in env['set']: - del env['set'][k] - env['add'] = [el for el in env['add'] if el[0] != k] - env['pre'] = [el for el in env['pre'] if el[0] != k] - - print "Forgot '%s' (for next session)" % k - - elif k.endswith('+'): - k = k[:-1] - env['add'].append((k,v)) - os.environ[k] += v - print k,"after append =",os.environ[k] - elif k.endswith('-'): - k = k[:-1] - env['pre'].append((k,v)) - os.environ[k] = v + os.environ.get(k,"") - print k,"after prepend =",os.environ[k] - - - else: - env['set'][k] = v - print "Setting",k,"to",v - os.environ[k] = v - - db['stored_env'] = env - -def env_completer(self,event): - """ Custom completer that lists all env vars """ - return os.environ.keys() - -ip.define_magic('env', persist_env) -ip.set_hook('complete_command',env_completer, str_key = '%env') - diff --git a/IPython/quarantine/ext_rescapture.py b/IPython/quarantine/ext_rescapture.py deleted file mode 100644 index da96bf8..0000000 --- a/IPython/quarantine/ext_rescapture.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -""" IPython extension: new prefilters for output grabbing - -Provides - -var = %magic blah blah - -var = !ls -""" - -from IPython.core import ipapi -from IPython.core.error import TryNext -from IPython.utils.text import make_quoted_expr -from IPython.utils.genutils import * - -ip = ipapi.get() - -import re - -def hnd_magic(line,mo): - """ Handle a = %mymagic blah blah """ - var = mo.group('varname') - cmd = mo.group('cmd') - expr = make_quoted_expr(cmd) - return itpl('$var = get_ipython().magic($expr)') - -def hnd_syscmd(line,mo): - """ Handle a = !ls """ - var = mo.group('varname') - cmd = mo.group('cmd') - expr = make_quoted_expr(itpl("sc -l =$cmd")) - return itpl('$var = get_ipython().magic($expr)') - -def install_re_handler(pat, hnd): - ip.meta.re_prefilters.append((re.compile(pat), hnd)) - -def init_handlers(): - - ip.meta.re_prefilters = [] - - install_re_handler('(?P[\w\.]+)\s*=\s*%(?P.*)', - hnd_magic - ) - - install_re_handler('(?P[\w\.]+)\s*=\s*!(?P.*)', - hnd_syscmd - ) - -init_handlers() - -def regex_prefilter_f(self,line): - for pat, handler in ip.meta.re_prefilters: - mo = pat.match(line) - if mo: - return handler(line,mo) - - raise TryNext - -ip.set_hook('input_prefilter', regex_prefilter_f) diff --git a/IPython/quarantine/ipy_app_completers.py b/IPython/quarantine/ipy_app_completers.py deleted file mode 100644 index 3a89b54..0000000 --- a/IPython/quarantine/ipy_app_completers.py +++ /dev/null @@ -1,19 +0,0 @@ -""" Install various IPython completers - -IPython extension that installs the completers related to external apps. - -The actual implementations are in extensions/ipy_completers.py - -""" -from IPython.core import ipapi - -ip = ipapi.get() - -from ipy_completers import * - -ip.set_hook('complete_command', apt_completer, re_key = '.*apt-get') -ip.set_hook('complete_command', svn_completer, str_key = 'svn') -ip.set_hook('complete_command', hg_completer, str_key = 'hg') - -# the old bzr completer is deprecated, we recommend ipy_bzr -#ip.set_hook('complete_command', bzr_completer, str_key = 'bzr') diff --git a/IPython/quarantine/ipy_completers.py b/IPython/quarantine/ipy_completers.py deleted file mode 100644 index dc822c7..0000000 --- a/IPython/quarantine/ipy_completers.py +++ /dev/null @@ -1,138 +0,0 @@ -""" Implementations for various useful completers - -See extensions/ipy_stock_completers.py on examples of how to enable a completer, -but the basic idea is to do: - -ip.set_hook('complete_command', svn_completer, str_key = 'svn') - -NOTE: some of the completers that used to be here, the ones used always by -default (loaded before by ipy_stock_completers) have been moved into -core.completerlib, where they will be further cleaned up and maintained. The -rest of this file would need to be well commented, cleaned up and tested for -inclusion into the core. -""" - -import glob,os,shlex,sys -import inspect -from time import time -from zipimport import zipimporter - -from IPython.core import ipapi -from IPython.core.error import TryNext -ip = ipapi.get() - -def vcs_completer(commands, event): - """ utility to make writing typical version control app completers easier - - VCS command line apps typically have the format: - - [sudo ]PROGNAME [help] [command] file file... - - """ - - - cmd_param = event.line.split() - if event.line.endswith(' '): - cmd_param.append('') - - if cmd_param[0] == 'sudo': - cmd_param = cmd_param[1:] - - if len(cmd_param) == 2 or 'help' in cmd_param: - return commands.split() - - return ip.Completer.file_matches(event.symbol) - - -svn_commands = """\ -add blame praise annotate ann cat checkout co cleanup commit ci copy -cp delete del remove rm diff di export help ? h import info list ls -lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit -pe propget pget pg proplist plist pl propset pset ps resolved revert -status stat st switch sw unlock update -""" - -def svn_completer(self,event): - return vcs_completer(svn_commands, event) - - -hg_commands = """ -add addremove annotate archive backout branch branches bundle cat -clone commit copy diff export grep heads help identify import incoming -init locate log manifest merge outgoing parents paths pull push -qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport -qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave -qselect qseries qtop qunapplied recover remove rename revert rollback -root serve showconfig status strip tag tags tip unbundle update verify -version -""" - -def hg_completer(self,event): - """ Completer for mercurial commands """ - - return vcs_completer(hg_commands, event) - - - -__bzr_commands = None - -def bzr_commands(): - global __bzr_commands - if __bzr_commands is not None: - return __bzr_commands - out = os.popen('bzr help commands') - __bzr_commands = [l.split()[0] for l in out] - return __bzr_commands - -def bzr_completer(self,event): - """ Completer for bazaar commands """ - cmd_param = event.line.split() - if event.line.endswith(' '): - cmd_param.append('') - - if len(cmd_param) > 2: - cmd = cmd_param[1] - param = cmd_param[-1] - output_file = (param == '--output=') - if cmd == 'help': - return bzr_commands() - elif cmd in ['bundle-revisions','conflicts', - 'deleted','nick','register-branch', - 'serve','unbind','upgrade','version', - 'whoami'] and not output_file: - return [] - else: - # the rest are probably file names - return ip.Completer.file_matches(event.symbol) - - return bzr_commands() - - -def apt_get_packages(prefix): - out = os.popen('apt-cache pkgnames') - for p in out: - if p.startswith(prefix): - yield p.rstrip() - - -apt_commands = """\ -update upgrade install remove purge source build-dep dist-upgrade -dselect-upgrade clean autoclean check""" - -def apt_completer(self, event): - """ Completer for apt-get (uses apt-cache internally) - - """ - - - cmd_param = event.line.split() - if event.line.endswith(' '): - cmd_param.append('') - - if cmd_param[0] == 'sudo': - cmd_param = cmd_param[1:] - - if len(cmd_param) == 2 or 'help' in cmd_param: - return apt_commands.split() - - return list(apt_get_packages(event.symbol)) diff --git a/IPython/quarantine/ipy_exportdb.py b/IPython/quarantine/ipy_exportdb.py deleted file mode 100644 index b6b3e6a..0000000 --- a/IPython/quarantine/ipy_exportdb.py +++ /dev/null @@ -1,77 +0,0 @@ -from IPython.core import ipapi -from IPython.core import macro -ip = ipapi.get() - -import os,pprint - -def export(filename = None): - - lines = ['import IPython.core.ipapi', 'ip = IPython.core.ipapi.get()',''] - - vars = ip.db.keys('autorestore/*') - vars.sort() - varstomove = [] - get = ip.db.get - - macros = [] - variables = [] - - for var in vars: - k = os.path.basename(var) - v = get(var) - - if k.startswith('_'): - continue - if isinstance(v, macro.Macro): - macros.append((k,v)) - if type(v) in [int, str, float]: - variables.append((k,v)) - - - - if macros: - lines.extend(['# === Macros ===' ,'']) - for k,v in macros: - lines.append("ip.defmacro('%s'," % k) - for line in v.value.splitlines(): - lines.append(' ' + repr(line+'\n')) - lines.extend([')', '']) - - if variables: - lines.extend(['','# === Variables ===','']) - for k,v in variables: - varstomove.append(k) - lines.append('%s = %s' % (k,repr(v))) - - lines.append('ip.push("%s")' % (' '.join(varstomove))) - - bkms = ip.db.get('bookmarks',{}) - - if bkms: - lines.extend(['','# === Bookmarks ===','']) - lines.append("ip.db['bookmarks'] = %s " % pprint.pformat(bkms, indent = 2) ) - - aliases = ip.db.get('stored_aliases', {} ) - - if aliases: - lines.extend(['','# === Alias definitions ===','']) - for k,v in aliases.items(): - try: - lines.append("ip.define_alias('%s', %s)" % (k, repr(v[1]))) - except (AttributeError, TypeError): - pass - - env = ip.db.get('stored_env') - if env: - lines.extend(['','# === Stored env vars ===','']) - lines.append("ip.db['stored_env'] = %s " % pprint.pformat(env, indent = 2) ) - - - - out = '\n'.join(lines) - - if filename: - open(filename,'w').write(out) - else: - print out - diff --git a/IPython/quarantine/ipy_extutil.py b/IPython/quarantine/ipy_extutil.py deleted file mode 100644 index 0b13ed2..0000000 --- a/IPython/quarantine/ipy_extutil.py +++ /dev/null @@ -1,44 +0,0 @@ -""" IPython extension management tools. - -After installation, you'll have the 'extutil' object in your namespace. -to. -""" - -# for the purposes of this module, every module that has the name 'ip' globally -# installed as below is an IPython extension - -from IPython.core import ipapi -ip = ipapi.get() -from IPython.core.iplib import InteractiveShell - -import sys,textwrap,inspect - -def indent(s, ind= ' '): - return '\n'.join([ind +l for l in s.splitlines()]) - -class ExtUtil: - """ IPython extensios (ipy_* etc.) management utilities """ - - def describe(self): - for n,mod in self._active(): - doc = inspect.getdoc(mod) - if doc: - print '== %s ==' % n - print indent(doc) - - - def ls(self): - """ Show list of installed extensions. """ - for n,m in self._active(): - print '%-20s %s' % (n,m.__file__.replace('\\','/')) - def _active(self): - act = [] - for mname,m in sys.modules.items(): - o = getattr(m, 'ip', None) - if isinstance(o, InteractiveShell): - act.append((mname,m)) - act.sort() - return act - -extutil = ExtUtil() -ip.push('extutil') diff --git a/IPython/quarantine/ipy_fsops.py b/IPython/quarantine/ipy_fsops.py deleted file mode 100644 index 0e7bffa..0000000 --- a/IPython/quarantine/ipy_fsops.py +++ /dev/null @@ -1,254 +0,0 @@ -""" File system operations - -Contains: Simple variants of normal unix shell commands (icp, imv, irm, -imkdir, igrep). - -Some "otherwise handy" utils ('collect' for gathering files to -~/_ipython/collect, 'inote' for collecting single note lines to -~/_ipython/note.txt) - -Mostly of use for bare windows installations where cygwin/equivalent is not -installed and you would otherwise need to deal with dos versions of the -commands (that e.g. don't understand / as path separator). These can -do some useful tricks on their own, though (like use 'mglob' patterns). - -Not to be confused with ipipe commands (ils etc.) that also start with i. - -QUARANTINE, NEEDS UPDATING TO THE NEW IPYTHON API TO WORK - -this depends on mglob that used to be in externals, -if this code is updated to run again with current IPython, you may need to -reintroduce that file back. In doing so, look for the possibility of achieving -the same effect only with the standard library (which may have improved by now, -since we currently depend on Python 2.6). -""" - -from IPython.core import ipapi -from IPython.core.error import TryNext -ip = ipapi.get() - -import shutil,os,shlex -from IPython.external import mglob -from IPython.external.path import path -from IPython.core.error import UsageError -import IPython.utils.generics - -def parse_args(args): - """ Given arg string 'CMD files... target', return ([files], target) """ - - tup = args.split(None, 1) - if len(tup) == 1: - raise UsageError("Expected arguments for " + tup[0]) - - tup2 = shlex.split(tup[1]) - - flist, trg = mglob.expand(tup2[0:-1]), tup2[-1] - if not flist: - raise UsageError("No files found:" + str(tup2[0:-1])) - return flist, trg - -def icp(ip,arg): - """ icp files... targetdir - - Copy all files to target, creating dirs for target if necessary - - icp srcdir dstdir - - Copy srcdir to distdir - - """ - import distutils.dir_util - - fs, targetdir = parse_args(arg) - if not os.path.isdir(targetdir) and len(fs) > 1: - distutils.dir_util.mkpath(targetdir,verbose =1) - for f in fs: - if os.path.isdir(f): - shutil.copytree(f, targetdir) - else: - shutil.copy2(f,targetdir) - return fs -ip.define_alias("icp",icp) - -def imv(ip,arg): - """ imv src tgt - - Move source to target. - """ - - fs, target = parse_args(arg) - if len(fs) > 1: - assert os.path.isdir(target) - for f in fs: - shutil.move(f, target) - return fs -ip.define_alias("imv",imv) - -def irm(ip,arg): - """ irm path[s]... - - Remove file[s] or dir[s] path. Dirs are deleted recursively. - """ - try: - paths = mglob.expand(arg.split(None,1)[1]) - except IndexError: - raise UsageError("%irm paths...") - import distutils.dir_util - for p in paths: - print "rm",p - if os.path.isdir(p): - distutils.dir_util.remove_tree(p, verbose = 1) - else: - os.remove(p) - -ip.define_alias("irm",irm) - -def imkdir(ip,arg): - """ imkdir path - - Creates dir path, and all dirs on the road - """ - import distutils.dir_util - targetdir = arg.split(None,1)[1] - distutils.dir_util.mkpath(targetdir,verbose =1) - -ip.define_alias("imkdir",imkdir) - -def igrep(ip,arg): - """ igrep PAT files... - - Very dumb file scan, case-insensitive. - - e.g. - - igrep "test this" rec:*.py - - """ - elems = shlex.split(arg) - dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:]) - res = [] - for f in fs: - found = False - for l in open(f): - if pat.lower() in l.lower(): - if not found: - print "[[",f,"]]" - found = True - res.append(f) - print l.rstrip() - return res - -ip.define_alias("igrep",igrep) - -def collect(ip,arg): - """ collect foo/a.txt rec:bar=*.py - - Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar, - likewise - - Without args, try to open ~/_ipython/collect dir (in win32 at least). - """ - from IPython.external.path import path - basedir = path(ip.ipython_dir + '/collect') - try: - fs = mglob.expand(arg.split(None,1)[1]) - except IndexError: - os.startfile(basedir) - return - for f in fs: - f = path(f) - trg = basedir / f.splitdrive()[1].lstrip('/\\') - if f.isdir(): - print "mkdir",trg - trg.makedirs() - continue - dname = trg.dirname() - if not dname.isdir(): - dname.makedirs() - print f,"=>",trg - shutil.copy2(f,trg) - -ip.define_alias("collect",collect) - -def inote(ip,arg): - """ inote Hello world - - Adds timestamp and Hello world to ~/_ipython/notes.txt - - Without args, opens notes.txt for editing. - """ - import time - fname = ip.ipython_dir + '/notes.txt' - - try: - entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n' - f= open(fname, 'a').write(entry) - except IndexError: - ip.hooks.editor(fname) - -ip.define_alias("inote",inote) - -def pathobj_mangle(p): - return p.replace(' ', '__').replace('.','DOT') -def pathobj_unmangle(s): - return s.replace('__',' ').replace('DOT','.') - - - -class PathObj(path): - def __init__(self,p): - self.path = p - if p != '.': - self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)] - else: - self.ents = None - def __complete__(self): - if self.path != '.': - return self.ents - self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')] - return self.ents - def __getattr__(self,name): - if name in self.ents: - if self.path.endswith('/'): - sep = '' - else: - sep = '/' - - tgt = self.path + sep + pathobj_unmangle(name) - #print "tgt",tgt - if os.path.isdir(tgt): - return PathObj(tgt) - if os.path.isfile(tgt): - return path(tgt) - - raise AttributeError, name # <<< DON'T FORGET THIS LINE !! - def __str__(self): - return self.path - - def __repr__(self): - return "" % self.path - - def __call__(self): - print "cd:",self.path - os.chdir(self.path) - -def complete_pathobj(obj, prev_completions): - if hasattr(obj,'__complete__'): - res = obj.__complete__() - if res: - return res - # just return normal attributes of 'path' object if the dir is empty - raise TryNext - -complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj) - -def test_pathobj(): - #p = PathObj('c:/prj') - #p2 = p.cgi - #print p,p2 - rootdir = PathObj("/") - startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs") - cwd = PathObj('.') - ip.push("rootdir startmenu cwd") - -#test_pathobj() diff --git a/IPython/quarantine/ipy_gnuglobal.py b/IPython/quarantine/ipy_gnuglobal.py deleted file mode 100644 index ac483f3..0000000 --- a/IPython/quarantine/ipy_gnuglobal.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -Add %global magic for GNU Global usage. - -http://www.gnu.org/software/global/ - -""" - -from IPython.core import ipapi -ip = ipapi.get() -import os - -# alter to your liking -global_bin = 'd:/opt/global/bin/global' - -def global_f(self,cmdline): - simple = 0 - if '-' not in cmdline: - cmdline = '-rx ' + cmdline - simple = 1 - - lines = [l.rstrip() for l in os.popen( global_bin + ' ' + cmdline ).readlines()] - - if simple: - parts = [l.split(None,3) for l in lines] - lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts] - print "\n".join(lines) - -ip.define_magic('global', global_f) - -def global_completer(self,event): - compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()] - return compl - -ip.set_hook('complete_command', global_completer, str_key = '%global') - diff --git a/IPython/quarantine/ipy_jot.py b/IPython/quarantine/ipy_jot.py deleted file mode 100644 index fce9099..0000000 --- a/IPython/quarantine/ipy_jot.py +++ /dev/null @@ -1,310 +0,0 @@ -# -*- coding: utf-8 -*- -""" -%jot magic for lightweight persistence. - -Stores variables in Struct with some notes in PicleShare database - - -""" - -from datetime import datetime -from IPython.core import ipapi -ip = ipapi.get() - -import pickleshare - -import inspect,pickle,os,sys,textwrap -from IPython.core.fakemodule import FakeModule -from IPython.utils.ipstruct import Struct -from IPython.utils.warn import error - - -def refresh_variables(ip, key=None): - db = ip.db - if key is None: - keys = db.keys('jot/*') - else: - keys = db.keys('jot/'+key) - for key in keys: - # strip autorestore - justkey = os.path.basename(key) - print "Restoring from", justkey, "..." - try: - obj = db[key] - except KeyError: - print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey - print "The error was:",sys.exc_info()[0] - else: - #print "restored",justkey,"=",obj #dbg - try: - origname = obj.name - except: - ip.user_ns[justkey] = obj - print "Restored", justkey - else: - ip.user_ns[origname] = obj['val'] - print "Restored", origname - -def read_variables(ip, key=None): - db = ip.db - if key is None: - return None - else: - keys = db.keys('jot/'+key) - for key in keys: - # strip autorestore - justkey = os.path.basename(key) - print "restoring from ", justkey - try: - obj = db[key] - except KeyError: - print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey - print "The error was:",sys.exc_info()[0] - else: - return obj - - -def detail_variables(ip, key=None): - db, get = ip.db, ip.db.get - - if key is None: - keys = db.keys('jot/*') - else: - keys = db.keys('jot/'+key) - if keys: - size = max(map(len,keys)) - else: - size = 0 - - fmthead = '%-'+str(size)+'s [%s]' - fmtbody = 'Comment:\n %s' - fmtdata = 'Data:\n %s, %s' - for key in keys: - v = get(key,'') - justkey = os.path.basename(key) - try: - print fmthead % (justkey, datetime.ctime(v.get('time',''))) - print fmtbody % (v.get('comment','')) - d = v.get('val','unavailable') - print fmtdata % (repr(type(d)), '') - print repr(d)[0:200] - print - print - except AttributeError: - print fmt % (justkey, '', '', repr(v)[:50]) - - -def intm(n): - try: - return int(n) - except: - return 0 - -def jot_obj(self, obj, name, comment=''): - """ - write obj data to the note database, with whatever that should be noted. - """ - had = self.db.keys('jot/'+name+'*') - # if it the same name but a later version, we stupidly add a number to the - # so the name doesn't collide. Any better idea? - suffix = '' - if len(had)>0: - pre = os.path.commonprefix(had) - suf = [n.split(pre)[1] for n in had] - versions = map(intm, suf) - suffix = str(max(versions)+1) - - uname = 'jot/'+name+suffix - - all = ip.shell.history_manager.input_hist_parsed - - # We may actually want to make snapshot of files that are run-ned. - - # get the comment - try: - comment = ip.magic_edit('-x').strip() - except: - print "No comment is recorded." - comment = '' - - self.db[uname] = Struct({'val':obj, - 'time' : datetime.now(), - 'hist' : all, - 'name' : name, - 'comment' : comment,}) - - print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__) - - - -def magic_jot(self, parameter_s=''): - """Lightweight persistence for python variables. - - Example: - - ville@badger[~]|1> A = ['hello',10,'world']\\ - ville@badger[~]|2> %jot A\\ - ville@badger[~]|3> Exit - - (IPython session is closed and started again...) - - ville@badger:~$ ipython -p pysh\\ - ville@badger[~]|1> print A - - ['hello', 10, 'world'] - - Usage: - - %jot - Show list of all variables and their current values\\ - %jot -l - Show list of all variables and their current values in detail\\ - %jot -l - Show one variable and its current values in detail\\ - %jot - Store the *current* value of the variable to disk\\ - %jot -d - Remove the variable and its value from storage\\ - %jot -z - Remove all variables from storage (disabled)\\ - %jot -r - Refresh/Load variable from jot (delete current vals)\\ - %jot foo >a.txt - Store value of foo to new file a.txt\\ - %jot foo >>a.txt - Append value of foo to file a.txt\\ - - It should be noted that if you change the value of a variable, you - need to %note it again if you want to persist the new value. - - Note also that the variables will need to be pickleable; most basic - python types can be safely %stored. - - """ - - opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') - args = argsl.split(None,1) - ip = self.getapi() - db = ip.db - # delete - if opts.has_key('d'): - try: - todel = args[0] - except IndexError: - error('You must provide the variable to forget') - else: - try: - del db['jot/' + todel] - except: - error("Can't delete variable '%s'" % todel) - # reset the whole database - elif opts.has_key('z'): - print "reseting the whole database has been disabled." - #for k in db.keys('autorestore/*'): - # del db[k] - - elif opts.has_key('r'): - try: - toret = args[0] - except: - print "restoring all the variables jotted down..." - refresh_variables(ip) - else: - refresh_variables(ip, toret) - - elif opts.has_key('l'): - try: - tolist = args[0] - except: - print "List details for all the items." - detail_variables(ip) - else: - print "Details for", tolist, ":" - detail_variables(ip, tolist) - - # run without arguments -> list noted variables & notes - elif not args: - vars = self.db.keys('jot/*') - vars.sort() - if vars: - size = max(map(len,vars)) - 4 - else: - size = 0 - - print 'Variables and their in-db values:' - fmt = '%-'+str(size)+'s [%s] -> %s' - get = db.get - for var in vars: - justkey = os.path.basename(var) - v = get(var,'') - try: - print fmt % (justkey,\ - datetime.ctime(v.get('time','')),\ - v.get('comment','')[:70].replace('\n',' '),) - except AttributeError: - print fmt % (justkey, '', '', repr(v)[:50]) - - - # default action - store the variable - else: - # %store foo >file.txt or >>file.txt - if len(args) > 1 and args[1].startswith('>'): - fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) - if args[1].startswith('>>'): - fil = open(fnam,'a') - else: - fil = open(fnam,'w') - obj = ip.ev(args[0]) - print "Writing '%s' (%s) to file '%s'." % (args[0], - obj.__class__.__name__, fnam) - - - if not isinstance (obj,basestring): - from pprint import pprint - pprint(obj,fil) - else: - fil.write(obj) - if not obj.endswith('\n'): - fil.write('\n') - - fil.close() - return - - # %note foo - try: - obj = ip.user_ns[args[0]] - except KeyError: - # this should not be alias, for aliases, use %store - print - print "Error: %s doesn't exist." % args[0] - print - print "Use %note -r to retrieve variables. This should not be used " +\ - "to store alias, for saving aliases, use %store" - return - else: - if isinstance(inspect.getmodule(obj), FakeModule): - print textwrap.dedent("""\ - Warning:%s is %s - Proper storage of interactively declared classes (or instances - of those classes) is not possible! Only instances - of classes in real modules on file system can be %%store'd. - """ % (args[0], obj) ) - return - #pickled = pickle.dumps(obj) - #self.db[ 'jot/' + args[0] ] = obj - jot_obj(self, obj, args[0]) - - -def magic_read(self, parameter_s=''): - """ - %read - Load variable from data that is jotted down.\\ - - """ - - opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') - args = argsl.split(None,1) - ip = self.getapi() - db = ip.db - #if opts.has_key('r'): - try: - toret = args[0] - except: - print "which record do you want to read out?" - return - else: - return read_variables(ip, toret) - - -ip.define_magic('jot',magic_jot) -ip.define_magic('read',magic_read) diff --git a/IPython/quarantine/ipy_lookfor.py b/IPython/quarantine/ipy_lookfor.py deleted file mode 100644 index 33729ce..0000000 --- a/IPython/quarantine/ipy_lookfor.py +++ /dev/null @@ -1,234 +0,0 @@ -""" -IPython extension: %lookfor command for searching docstrings - -""" -# Pauli Virtanen , 2008. - -import re, inspect, pkgutil, pydoc - -#------------------------------------------------------------------------------ -# Lookfor functionality -#------------------------------------------------------------------------------ - -# Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...} -# where kind: "func", "class", "module", "object" -# and index: index in breadth-first namespace traversal -_lookfor_caches = {} - -# regexp whose match indicates that the string may contain a function signature -_function_signature_re = re.compile(r"[a-z_]+\(.*[,=].*\)", re.I) - -def lookfor(what, modules=None, import_modules=True, regenerate=False): - """ - Search for objects whose documentation contains all given words. - Shows a summary of matching objects, sorted roughly by relevance. - - Parameters - ---------- - what : str - String containing words to look for. - - module : str, module - Module whose docstrings to go through. - import_modules : bool - Whether to import sub-modules in packages. - Will import only modules in __all__ - regenerate: bool - Re-generate the docstring cache - - """ - # Cache - cache = {} - for module in modules: - try: - c = _lookfor_generate_cache(module, import_modules, regenerate) - cache.update(c) - except ImportError: - pass - - # Search - # XXX: maybe using a real stemming search engine would be better? - found = [] - whats = str(what).lower().split() - if not whats: return - - for name, (docstring, kind, index) in cache.iteritems(): - if kind in ('module', 'object'): - # don't show modules or objects - continue - ok = True - doc = docstring.lower() - for w in whats: - if w not in doc: - ok = False - break - if ok: - found.append(name) - - # Relevance sort - # XXX: this is full Harrison-Stetson heuristics now, - # XXX: it probably could be improved - - kind_relevance = {'func': 1000, 'class': 1000, - 'module': -1000, 'object': -1000} - - def relevance(name, docstr, kind, index): - r = 0 - # do the keywords occur within the start of the docstring? - first_doc = "\n".join(docstr.lower().strip().split("\n")[:3]) - r += sum([200 for w in whats if w in first_doc]) - # do the keywords occur in the function name? - r += sum([30 for w in whats if w in name]) - # is the full name long? - r += -len(name) * 5 - # is the object of bad type? - r += kind_relevance.get(kind, -1000) - # is the object deep in namespace hierarchy? - r += -name.count('.') * 10 - r += max(-index / 100, -100) - return r - - def relevance_sort(a, b): - dr = relevance(b, *cache[b]) - relevance(a, *cache[a]) - if dr != 0: return dr - else: return cmp(a, b) - found.sort(relevance_sort) - - # Pretty-print - s = "Search results for '%s'" % (' '.join(whats)) - help_text = [s, "-"*len(s)] - for name in found: - doc, kind, ix = cache[name] - - doclines = [line.strip() for line in doc.strip().split("\n") - if line.strip()] - - # find a suitable short description - try: - first_doc = doclines[0].strip() - if _function_signature_re.search(first_doc): - first_doc = doclines[1].strip() - except IndexError: - first_doc = "" - help_text.append("%s\n %s" % (name, first_doc)) - - # Output - if len(help_text) > 10: - pager = pydoc.getpager() - pager("\n".join(help_text)) - else: - print "\n".join(help_text) - -def _lookfor_generate_cache(module, import_modules, regenerate): - """ - Generate docstring cache for given module. - - Parameters - ---------- - module : str, None, module - Module for which to generate docstring cache - import_modules : bool - Whether to import sub-modules in packages. - Will import only modules in __all__ - regenerate: bool - Re-generate the docstring cache - - Returns - ------- - cache : dict {obj_full_name: (docstring, kind, index), ...} - Docstring cache for the module, either cached one (regenerate=False) - or newly generated. - - """ - global _lookfor_caches - - if module is None: - module = "numpy" - - if isinstance(module, str): - module = __import__(module) - - if id(module) in _lookfor_caches and not regenerate: - return _lookfor_caches[id(module)] - - # walk items and collect docstrings - cache = {} - _lookfor_caches[id(module)] = cache - seen = {} - index = 0 - stack = [(module.__name__, module)] - while stack: - name, item = stack.pop(0) - if id(item) in seen: continue - seen[id(item)] = True - - index += 1 - kind = "object" - - if inspect.ismodule(item): - kind = "module" - try: - _all = item.__all__ - except AttributeError: - _all = None - # import sub-packages - if import_modules and hasattr(item, '__path__'): - for m in pkgutil.iter_modules(item.__path__): - if _all is not None and m[1] not in _all: - continue - try: - __import__("%s.%s" % (name, m[1])) - except ImportError: - continue - for n, v in inspect.getmembers(item): - if _all is not None and n not in _all: - continue - stack.append(("%s.%s" % (name, n), v)) - elif inspect.isclass(item): - kind = "class" - for n, v in inspect.getmembers(item): - stack.append(("%s.%s" % (name, n), v)) - elif callable(item): - kind = "func" - - doc = inspect.getdoc(item) - if doc is not None: - cache[name] = (doc, kind, index) - - return cache - -#------------------------------------------------------------------------------ -# IPython connectivity -#------------------------------------------------------------------------------ - -from IPython.core import ipapi -ip = ipapi.get() - -_lookfor_modules = ['numpy', 'scipy'] - -def lookfor_f(self, arg=''): - r""" - Search for objects whose documentation contains all given words. - Shows a summary of matching objects, sorted roughly by relevance. - - Usage - ----- - %lookfor +numpy some words - Search module 'numpy' - - %lookfor_modules numpy scipy - Set default modules whose docstrings to search - - """ - lookfor(arg, modules=_lookfor_modules) - -def lookfor_modules_f(self, arg=''): - global _lookfor_modules - if not arg: - print "Modules included in %lookfor search:", _lookfor_modules - else: - _lookfor_modules = arg.split() - -ip.define_magic('lookfor', lookfor_f) -ip.define_magic('lookfor_modules', lookfor_modules_f) - diff --git a/IPython/quarantine/ipy_profile_doctest.py b/IPython/quarantine/ipy_profile_doctest.py deleted file mode 100644 index b14ee7c..0000000 --- a/IPython/quarantine/ipy_profile_doctest.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Config file for 'doctest' profile. - -This profile modifies the prompts to be the standard Python ones, so that you -can generate easily doctests from an IPython session. - -But more importantly, it enables pasting of code with '>>>' prompts and -arbitrary initial whitespace, as is typical of doctests in reST files and -docstrings. This allows you to easily re-run existing doctests and iteratively -work on them as part of your development workflow. - -The exception mode is also set to 'plain' so the generated exceptions are as -similar as possible to the default Python ones, for inclusion in doctests.""" - -# get various stuff that are there for historical / familiarity reasons -import ipy_legacy - -from IPython.core import ipapi - -from IPython.extensions import InterpreterPasteInput - -def main(): - ip = ipapi.get() - o = ip.options - - # Set the prompts similar to the defaults - o.prompt_in1 = '>>> ' - o.prompt_in2 = '... ' - o.prompt_out = '' - - # Add a blank line before each new set of inputs. This is needed by - # doctest to distinguish each test from the next. - o.separate_in = '\n' - o.separate_out = '' - o.separate_out2 = '' - - # Disable pprint, so that outputs are printed as similarly to standard - # python as possible - o.pprint = False - - # Use plain exceptions, to also resemble normal python. - o.xmode = 'plain' - - # Store the activity flag in the metadata bag from the running shell - ip.meta.doctest_mode = True - -main() diff --git a/IPython/quarantine/ipy_pydb.py b/IPython/quarantine/ipy_pydb.py deleted file mode 100644 index 67b45f0..0000000 --- a/IPython/quarantine/ipy_pydb.py +++ /dev/null @@ -1,31 +0,0 @@ -import inspect -from IPython.core import ipapi -from IPython.utils.process import arg_split -ip = ipapi.get() - -from IPython.core import debugger - -def call_pydb(self, args): - """Invoke pydb with the supplied parameters.""" - try: - import pydb - except ImportError: - raise ImportError("pydb doesn't seem to be installed.") - - if not hasattr(pydb.pydb, "runv"): - raise ImportError("You need pydb version 1.19 or later installed.") - - argl = arg_split(args) - # print argl # dbg - if len(inspect.getargspec(pydb.runv)[0]) == 2: - pdb = debugger.Pdb(color_scheme=self.colors) - ip.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )() - else: - ip.history_saving_wrapper( lambda : pydb.runv(argl) )() - - -ip.define_magic("pydb",call_pydb) - - - - diff --git a/IPython/quarantine/ipy_rehashdir.py b/IPython/quarantine/ipy_rehashdir.py deleted file mode 100644 index 3c7cbd2..0000000 --- a/IPython/quarantine/ipy_rehashdir.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -""" IPython extension: add %rehashdir magic - -Usage: - -%rehashdir c:/bin c:/tools - - Add all executables under c:/bin and c:/tools to alias table, in - order to make them directly executable from any directory. - -This also serves as an example on how to extend ipython -with new magic functions. - -Unlike rest of ipython, this requires Python 2.4 (optional -extensions are allowed to do that). - -""" - -from IPython.core import ipapi -ip = ipapi.get() - - -import os,re,fnmatch,sys - -def selflaunch(ip,line): - """ Launch python script with 'this' interpreter - - e.g. d:\foo\ipykit.exe a.py - - """ - - tup = line.split(None,1) - if len(tup) == 1: - print "Launching nested ipython session" - os.system(sys.executable) - return - - cmd = sys.executable + ' ' + tup[1] - print ">",cmd - os.system(cmd) - -class PyLauncher: - """ Invoke selflanucher on the specified script - - This is mostly useful for associating with scripts using:: - _ip.define_alias('foo',PyLauncher('foo_script.py')) - - """ - def __init__(self,script): - self.script = os.path.abspath(script) - def __call__(self, ip, line): - if self.script.endswith('.ipy'): - ip.runlines(open(self.script).read()) - else: - # first word is the script/alias name itself, strip it - tup = line.split(None,1) - if len(tup) == 2: - tail = ' ' + tup[1] - else: - tail = '' - - selflaunch(ip,"py " + self.script + tail) - def __repr__(self): - return 'PyLauncher("%s")' % self.script - -def rehashdir_f(self,arg): - """ Add executables in all specified dirs to alias table - - Usage: - - %rehashdir c:/bin;c:/tools - - Add all executables under c:/bin and c:/tools to alias table, in - order to make them directly executable from any directory. - - Without arguments, add all executables in current directory. - - """ - - # most of the code copied from Magic.magic_rehashx - - def isjunk(fname): - junk = ['*~'] - for j in junk: - if fnmatch.fnmatch(fname, j): - return True - return False - - created = [] - if not arg: - arg = '.' - path = map(os.path.abspath,arg.split(';')) - alias_table = self.shell.alias_manager.alias_table - - if os.name == 'posix': - isexec = lambda fname:os.path.isfile(fname) and \ - os.access(fname,os.X_OK) - else: - - try: - winext = os.environ['pathext'].replace(';','|').replace('.','') - except KeyError: - winext = 'exe|com|bat|py' - if 'py' not in winext: - winext += '|py' - - execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) - isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) - savedir = os.getcwdu() - try: - # write the whole loop for posix/Windows so we don't have an if in - # the innermost part - if os.name == 'posix': - for pdir in path: - os.chdir(pdir) - for ff in os.listdir(pdir): - if isexec(ff) and not isjunk(ff): - # each entry in the alias table must be (N,name), - # where N is the number of positional arguments of the - # alias. - src,tgt = os.path.splitext(ff)[0], os.path.abspath(ff) - created.append(src) - alias_table[src] = (0,tgt) - else: - for pdir in path: - os.chdir(pdir) - for ff in os.listdir(pdir): - if isexec(ff) and not isjunk(ff): - src, tgt = execre.sub(r'\1',ff), os.path.abspath(ff) - src = src.lower() - created.append(src) - alias_table[src] = (0,tgt) - # Make sure the alias table doesn't contain keywords or builtins - self.shell.alias_table_validate() - # Call again init_auto_alias() so we get 'rm -i' and other - # modified aliases since %rehashx will probably clobber them - # self.shell.init_auto_alias() - finally: - os.chdir(savedir) - return created - -ip.define_magic("rehashdir",rehashdir_f) diff --git a/IPython/quarantine/ipy_render.py b/IPython/quarantine/ipy_render.py deleted file mode 100644 index a5b98fb..0000000 --- a/IPython/quarantine/ipy_render.py +++ /dev/null @@ -1,67 +0,0 @@ -""" IPython extension: Render templates from variables and paste to clipbard """ - -from IPython.core import ipapi - -ip = ipapi.get() - -from string import Template -import sys,os - -# We no longer bundle Itpl. If you update this module, you should use advanced -# string formatting instead. -from IPython.external.Itpl import itplns - -def toclip_w32(s): - """ Places contents of s to clipboard - - Needs pyvin32 to work: - http://sourceforge.net/projects/pywin32/ - """ - import win32clipboard as cl - import win32con - cl.OpenClipboard() - cl.EmptyClipboard() - cl.SetClipboardText( s.replace('\n','\r\n' )) - cl.CloseClipboard() - -try: - import win32clipboard - toclip = toclip_w32 -except ImportError: - def toclip(s): pass - - -def render(tmpl): - """ Render a template (Itpl format) from ipython variables - - Example: - - $ import ipy_render - $ my_name = 'Bob' # %store this for convenience - $ t_submission_form = "Submission report, author: $my_name" # %store also - $ render t_submission_form - - => returns "Submission report, author: Bob" and copies to clipboard on win32 - - # if template exist as a file, read it. Note: ;f hei vaan => f("hei vaan") - $ ;render c:/templates/greeting.txt - - Template examples (Ka-Ping Yee's Itpl library): - - Here is a $string. - Here is a $module.member. - Here is an $object.member. - Here is a $functioncall(with, arguments). - Here is an ${arbitrary + expression}. - Here is an $array[3] member. - Here is a $dictionary['member']. - """ - - if os.path.isfile(tmpl): - tmpl = open(tmpl).read() - - res = itplns(tmpl, ip.user_ns) - toclip(res) - return res - -ip.push('render') diff --git a/IPython/quarantine/ipy_server.py b/IPython/quarantine/ipy_server.py deleted file mode 100644 index ba1c12f..0000000 --- a/IPython/quarantine/ipy_server.py +++ /dev/null @@ -1,38 +0,0 @@ -""" Simple TCP socket server that executes statements in IPython instance. - -Usage: - -import ipy_server -ipy_server.serve_thread(16455) - -Now, to execute the statements in this ipython instance, open a TCP socket -(port 16455), write out the statements, and close the socket. -You can use e.g. "telnet localhost 16455" or a script to do this. - -This is a bit like 'M-x server-start" or gnuserv in the emacs world. - -""" - -from IPython.core import ipapi -ip = ipapi.get() - -import SocketServer - -# user-accessible port -PORT = 8099 - -class IPythonRequestHandler(SocketServer.StreamRequestHandler): - def handle(self): - #print "connection from", self.client_address - inp = self.rfile.read().replace('\r\n','\n') - #print "Execute",inp - ip.runlines(inp) - -def serve(port = PORT): - server = SocketServer.TCPServer(("", port), IPythonRequestHandler) - print "ipy_server on TCP port", port - server.serve_forever() - -def serve_thread(port = PORT): - import thread - thread.start_new_thread(serve, (port,)) \ No newline at end of file diff --git a/IPython/quarantine/ipy_signals.py b/IPython/quarantine/ipy_signals.py deleted file mode 100644 index 64478db..0000000 --- a/IPython/quarantine/ipy_signals.py +++ /dev/null @@ -1,61 +0,0 @@ -""" Advanced signal (e.g. ctrl+C) handling for IPython - -So far, this only ignores ctrl + C in IPython file a subprocess -is executing, to get closer to how a "proper" shell behaves. - -Other signal processing may be implemented later on. - -If _ip.options.verbose is true, show exit status if nonzero - -""" - -import signal,os,sys -from IPython.core import ipapi -import subprocess - -ip = ipapi.get() - -def new_ipsystem_posix(cmd): - """ ctrl+c ignoring replacement for system() command in iplib. - - Ignore ctrl + c in IPython process during the command execution. - The subprocess will still get the ctrl + c signal. - - posix implementation - """ - - p = subprocess.Popen(cmd, shell = True) - - old_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) - pid,status = os.waitpid(p.pid,0) - signal.signal(signal.SIGINT, old_handler) - if status and ip.options.verbose: - print "[exit status: %d]" % status - -def new_ipsystem_win32(cmd): - """ ctrl+c ignoring replacement for system() command in iplib. - - Ignore ctrl + c in IPython process during the command execution. - The subprocess will still get the ctrl + c signal. - - win32 implementation - """ - old_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) - status = os.system(cmd) - signal.signal(signal.SIGINT, old_handler) - if status and ip.options.verbose: - print "[exit status: %d]" % status - - -def init(): - o = ip.options - try: - o.verbose - except AttributeError: - o.allow_new_attr (True ) - o.verbose = 0 - - ip.system = (sys.platform == 'win32' and new_ipsystem_win32 or - new_ipsystem_posix) - -init() diff --git a/IPython/quarantine/ipy_synchronize_with.py b/IPython/quarantine/ipy_synchronize_with.py deleted file mode 100644 index eed130e..0000000 --- a/IPython/quarantine/ipy_synchronize_with.py +++ /dev/null @@ -1,242 +0,0 @@ -from IPython.core import ipapi -ip = ipapi.get() - -import win32api -import win32ui -import win32console -import dde -import os -import scitedirector - -# test to write. - -def set_hook(synchronize_with_editor): - """Set the synchronize with editor hook with a callable object. - - The callable object will be called with the following arguments when - IPython wants to synchronize with you favorite editor: - - - ip: a running IPython instance. - - - filename: the path of the file the editor is supposed to display. - - - lineno : the line number of the line the editor is supposed to - highlight. - - - columnno : the column number of the character the editor is supposed - to highlight. - """ - ip.set_hook("synchronize_with_editor", synchronize_with_editor) - - -def find_filename(filename): - """Return the filename to synchronize with based on """ - filename = os.path.splitext(filename) - if filename[1] == ".pyc": - filename = (filename[0], ".py") - filename = "".join(filename) - - if not os.path.isabs(filename): - filename = os.path.join(os.getcwdu(), filename) - - if os.path.isfile(filename): - return filename - - return "" - - -def run_command(path, command, arguments, asynchronous = True): - """Run a shell command and return the exit code of the command""" - # This is a thin wrapper around os.system that: - # - Let you run command asynchronously. - # - Accept spaces in command path. - # - Dont throw exception if the command don't exist. - line = '' - if asynchronous: - line += 'start ' - - try: - line += win32api.GetShortPathName(os.path.join(path, command) + ".exe") + " " - except: - print 'could not find: "%s"' % (os.path.join(path, command) + ".exe") - return -1 - - line += arguments - r = os.system(line) - return r - - -def sleep(milliseconds): - """Wait some milliseconds.""" - # This is used to make sure the editor did its job before we reset the focus on the console. - win32api.Sleep(milliseconds) - - -def restore_console_focus(): - """Restore the focus to the IPython console.""" - h = win32console.GetConsoleWindow() - console_window = win32ui.CreateWindowFromHandle(h) - console_window.SetForegroundWindow() - - -# This is the most simple example of hook: -class GVimHook: - def __init__(self, path, wakeup_duration): - self.path = path - self.wakeup_duration = wakeup_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - run_command(self.path, 'gvim', '--remote-silent +%d "%s"' % (lineno, filename)) - - sleep(self.wakeup_duration) - - restore_console_focus() - - -def gvim(path = r"C:\Program Files\vim\vim71", wakeup_duration = 100): - synchronize_with_editor = GVimHook(path, wakeup_duration) - set_hook(synchronize_with_editor) - - -class EmacsHook: - def __init__(self, path, wakeup_duration, start_duration): - self.path = path - self.wakeup_duration = wakeup_duration - self.start_duration = start_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - r = run_command(self.path, "emacsclient", '-n +%d:%d "%s" 2>nul' % (lineno, columnno, filename), False) - if r != 0: - run_command(self.path, 'runemacs', '--quick -f server-start +%d:%d "%s"' % (lineno, columnno, filename)) - sleep(self.start_duration) - else: - sleep(self.wakeup_duration) - - restore_console_focus() - - -def emacs(path = r"C:\Program Files\emacs\bin", wakeup_duration = 100, start_duration = 2000): - synchronize_with_editor = EmacsHook(path, wakeup_duration, start_duration) - set_hook(synchronize_with_editor) - - -class SciteHook: - def __init__(self, path, wakeup_duration, start_duration): - self.path = path - self.wakeup_duration = wakeup_duration - self.start_duration = start_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - scites = scitedirector.findWindows() - if not scites: - run_command(self.path, "scite", '"-open:%s" -goto:%d' % (filename.replace("\\", "/"), lineno)) - - sleep(self.start_duration) - restore_console_focus() - else: - scite = scites[0] - scitedirector.sendCommand(scite, 'open:%s' % filename.replace("\\", "/")) - scitedirector.sendCommand(scite, "goto:%d" % lineno) - - -def scite(path = r"C:\Program Files\SciTE Source Code Editor", wakeup_duration = 100, start_duration = 500): - synchronize_with_editor = SciteHook(path, wakeup_duration, start_duration) - set_hook(synchronize_with_editor) - - -class NodePadPlusPlusHook: - def __init__(self, path, wakeup_duration): - self.path = path - self.wakeup_duration = wakeup_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - run_command(self.path, "notepad++", '"%s" -n%d' % (filename, lineno)) - - sleep(self.wakeup_duration) - - restore_console_focus() - - -def notepadplusplus(path = r"C:\Program Files\Notepad++", wakeup_duration = 100): - synchronize_with_editor = NodePadPlusPlusHook(path, wakeup_duration) - set_hook(synchronize_with_editor) - - -class PsPadHook: - def __init__(self, path, wakeup_duration): - self.path = path - self.wakeup_duration = wakeup_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - run_command(self.path, "pspad", '"%s" -%d' % (filename, lineno)) - - sleep(self.wakeup_duration) - - restore_console_focus() - - -def pspad(path = r"C:\Program Files\PSPad editor", wakeup_duration = 100): - synchronize_with_editor = PsPadHook(path, wakeup_duration) - set_hook(synchronize_with_editor) - - -# This is an example of DDE hook: -class UltraEditHook: - def __init__(self, path, wakeup_duration, start_duration): - self.path = path - self.wakeup_duration = wakeup_duration - self.start_duration = start_duration - - def __call__(self, ip, filename, lineno, columnno): - filename = find_filename(filename) - - if not filename: - return - - server = dde.CreateServer() - server.Create("myddeserver") - conversation = dde.CreateConversation(server) - try: - conversation.ConnectTo("uedit32", "System") - conversation.Exec(r'[open("%s/%d"])' % (filename, lineno)) - - sleep(self.wakeup_duration) - except: - run_command(self.path, 'uedit32', '"%s/%d"' % (filename, lineno)) - - sleep(self.start_duration) - - server.Shutdown() - - restore_console_focus() - - -def ultraedit(path = r"C:\Program Files\IDM Computer Solutions\UltraEdit-32", wakeup_duration = 10, start_duration = 2000): - synchronize_with_editor = UltraEditHook(path, wakeup_duration, start_duration) - set_hook(synchronize_with_editor) - \ No newline at end of file diff --git a/IPython/quarantine/ipy_system_conf.py b/IPython/quarantine/ipy_system_conf.py deleted file mode 100644 index 1bda585..0000000 --- a/IPython/quarantine/ipy_system_conf.py +++ /dev/null @@ -1,24 +0,0 @@ -""" System wide configuration file for IPython. - -This will be imported by ipython for all users. - -After this ipy_user_conf.py is imported, user specific configuration -should reside there. - - """ - -from IPython.core import ipapi -ip = ipapi.get() - -# add system wide configuration information, import extensions etc. here. -# nothing here is essential - -import sys - -import ext_rescapture # var = !ls and var = %magic -import pspersistence # %store magic -import clearcmd # %clear - -import ipy_stock_completers - -ip.load('IPython.core.history') diff --git a/IPython/quarantine/ipy_which.py b/IPython/quarantine/ipy_which.py deleted file mode 100644 index efe7449..0000000 --- a/IPython/quarantine/ipy_which.py +++ /dev/null @@ -1,76 +0,0 @@ -r""" %which magic command - -%which => search PATH for files matching PATH. Also scans aliases - -""" - -from IPython.core import ipapi -ip = ipapi.get() - -import os,sys -from fnmatch import fnmatch -def which(fname): - fullpath = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) - - if '.' not in fullpath: - fullpath = ['.'] + fullpath - fn = fname - for p in fullpath: - for f in os.listdir(p): - head, ext = os.path.splitext(f) - if f == fn or fnmatch(head, fn): - yield os.path.join(p,f) - return - -def which_alias(fname): - for al, tgt in ip.alias_table.items(): - if not (al == fname or fnmatch(al, fname)): - continue - if callable(tgt): - print "Callable alias",tgt - d = tgt.__doc__ - if d: - print "Docstring:\n",d - continue - trg = tgt[1] - - trans = ip.expand_alias(trg) - cmd = trans.split(None,1)[0] - print al,"->",trans - for realcmd in which(cmd): - print " ==",realcmd - -def which_f(self, arg): - r""" %which => search PATH for files matching cmd. Also scans aliases. - - Traverses PATH and prints all files (not just executables!) that match the - pattern on command line. Probably more useful in finding stuff - interactively than 'which', which only prints the first matching item. - - Also discovers and expands aliases, so you'll see what will be executed - when you call an alias. - - Example: - - [~]|62> %which d - d -> ls -F --color=auto - == c:\cygwin\bin\ls.exe - c:\cygwin\bin\d.exe - - [~]|64> %which diff* - diff3 -> diff3 - == c:\cygwin\bin\diff3.exe - diff -> diff - == c:\cygwin\bin\diff.exe - c:\cygwin\bin\diff.exe - c:\cygwin\bin\diff3.exe - - """ - - which_alias(arg) - - for e in which(arg): - print e - -ip.define_magic("which",which_f) - diff --git a/IPython/quarantine/ipy_winpdb.py b/IPython/quarantine/ipy_winpdb.py deleted file mode 100644 index d59de7c..0000000 --- a/IPython/quarantine/ipy_winpdb.py +++ /dev/null @@ -1,84 +0,0 @@ -""" Debug a script (like %run -d) in IPython process, Using WinPdb - -Usage: - -%wdb test.py - run test.py, with a winpdb breakpoint at start of the file - -%wdb pass - Change the password (e.g. if you have forgotten the old one) - - -Notes ------ - -**WARNING**: As of March 2009 (IPython 0.10), WinPdb has a known bug, which -causes PyTables to become impossible to import if winpdb is loaded. Therefore, -if you need PyTables, do *not* use this extension. - -For more details: https://bugs.launchpad.net/ipython/+bug/249036 -""" - -import os - -from IPython.core import ipapi -from IPython.core.error import UsageError -import rpdb2 - -ip = ipapi.get() - -rpdb_started = False - -def wdb_f(self, arg): - """ Debug a script (like %run -d) in IPython process, Using WinPdb - - Usage: - - %wdb test.py - run test.py, with a winpdb breakpoint at start of the file - - %wdb pass - Change the password (e.g. if you have forgotten the old one) - - Note that after the script has been run, you need to do "Go" (f5) - in WinPdb to resume normal IPython operation. - """ - - global rpdb_started - if not arg.strip(): - print __doc__ - return - - if arg.strip() == 'pass': - passwd = raw_input('Enter new winpdb session password: ') - ip.db['winpdb_pass'] = passwd - print "Winpdb password changed" - if rpdb_started: - print "You need to restart IPython to use the new password" - return - - path = os.path.abspath(arg) - if not os.path.isfile(path): - raise UsageError("%%wdb: file %s does not exist" % path) - if not rpdb_started: - passwd = ip.db.get('winpdb_pass', None) - if passwd is None: - import textwrap - print textwrap.dedent("""\ - Winpdb sessions need a password that you use for attaching the external - winpdb session. IPython will remember this. You can change the password later - by '%wpdb pass' - """) - passwd = raw_input('Enter new winpdb session password: ') - ip.db['winpdb_pass'] = passwd - - print "Starting rpdb2 in IPython process" - rpdb2.start_embedded_debugger(passwd, timeout = 0) - rpdb_started = True - - rpdb2.set_temp_breakpoint(path) - print 'It is time to attach with WinPdb (launch WinPdb if needed, File -> Attach)' - ip.magic('%run ' + arg) - - -ip.define_magic('wdb', wdb_f) diff --git a/IPython/quarantine/ipy_workdir.py b/IPython/quarantine/ipy_workdir.py deleted file mode 100644 index 539bb21..0000000 --- a/IPython/quarantine/ipy_workdir.py +++ /dev/null @@ -1,41 +0,0 @@ -from IPython.core import ipapi -ip = ipapi.get() - -import os, subprocess - -workdir = None -def workdir_f(ip,line): - """ Exceute commands residing in cwd elsewhere - - Example:: - - workdir /myfiles - cd bin - workdir myscript.py - - executes myscript.py (stored in bin, but not in path) in /myfiles - """ - global workdir - dummy,cmd = line.split(None,1) - if os.path.isdir(cmd): - workdir = os.path.abspath(cmd) - print "Set workdir",workdir - elif workdir is None: - print "Please set workdir first by doing e.g. 'workdir q:/'" - else: - sp = cmd.split(None,1) - if len(sp) == 1: - head, tail = cmd, '' - else: - head, tail = sp - if os.path.isfile(head): - cmd = os.path.abspath(head) + ' ' + tail - print "Execute command '" + cmd+ "' in",workdir - olddir = os.getcwdu() - os.chdir(workdir) - try: - os.system(cmd) - finally: - os.chdir(olddir) - -ip.define_alias("workdir",workdir_f) diff --git a/IPython/quarantine/jobctrl.py b/IPython/quarantine/jobctrl.py deleted file mode 100644 index d687fb6..0000000 --- a/IPython/quarantine/jobctrl.py +++ /dev/null @@ -1,242 +0,0 @@ -""" Preliminary "job control" extensions for IPython - -requires python 2.4 (or separate 'subprocess' module - -This provides 2 features, launching background jobs and killing foreground jobs from another IPython instance. - -Launching background jobs: - - Usage: - - [ipython]|2> import jobctrl - [ipython]|3> &ls - <3> - [ipython]|4> _3.go - -----------> _3.go() - ChangeLog - IPython - MANIFEST.in - README - README_Windows.txt - - ... - -Killing foreground tasks: - -Launch IPython instance, run a blocking command: - - [Q:/ipython]|1> import jobctrl - [Q:/ipython]|2> cat - -Now launch a new IPython prompt and kill the process: - - IPython 0.8.3.svn.r2919 [on Py 2.5] - [Q:/ipython]|1> import jobctrl - [Q:/ipython]|2> %tasks - 6020: 'cat ' (Q:\ipython) - [Q:/ipython]|3> %kill - SUCCESS: The process with PID 6020 has been terminated. - [Q:/ipython]|4> - -(you don't need to specify PID for %kill if only one task is running) -""" - -from subprocess import * -import os,shlex,sys,time -import threading,Queue - -from IPython.core import ipapi -from IPython.core.error import TryNext -from IPython.utils.text import make_quoted_expr - -if os.name == 'nt': - def kill_process(pid): - os.system('taskkill /F /PID %d' % pid) -else: - def kill_process(pid): - os.system('kill -9 %d' % pid) - - - -class IpyPopen(Popen): - def go(self): - print self.communicate()[0] - def __repr__(self): - return '' % (self.line, self.pid) - - def kill(self): - kill_process(self.pid) - -def startjob(job): - p = IpyPopen(shlex.split(job), stdout=PIPE, shell = False) - p.line = job - return p - -class AsyncJobQ(threading.Thread): - def __init__(self): - threading.Thread.__init__(self) - self.q = Queue.Queue() - self.output = [] - self.stop = False - def run(self): - while 1: - cmd,cwd = self.q.get() - if self.stop: - self.output.append("** Discarding: '%s' - %s" % (cmd,cwd)) - continue - self.output.append("** Task started: '%s' - %s" % (cmd,cwd)) - - p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd = cwd) - out = p.stdout.read() - self.output.append("** Task complete: '%s'\n" % cmd) - self.output.append(out) - - def add(self,cmd): - self.q.put_nowait((cmd, os.getcwdu())) - - def dumpoutput(self): - while self.output: - item = self.output.pop(0) - print item - -_jobq = None - -def jobqueue_f(self, line): - - global _jobq - if not _jobq: - print "Starting jobqueue - do '&some_long_lasting_system_command' to enqueue" - _jobq = AsyncJobQ() - _jobq.setDaemon(True) - _jobq.start() - ip.jobq = _jobq.add - return - if line.strip() == 'stop': - print "Stopping and clearing jobqueue, %jobqueue start to start again" - _jobq.stop = True - return - if line.strip() == 'start': - _jobq.stop = False - return - -def jobctrl_prefilter_f(self,line): - if line.startswith('&'): - pre,fn,rest = self.split_user_input(line[1:]) - - line = ip.expand_aliases(fn,rest) - if not _jobq: - return 'get_ipython().startjob(%s)' % make_quoted_expr(line) - return 'get_ipython().jobq(%s)' % make_quoted_expr(line) - - raise TryNext - -def jobq_output_hook(self): - if not _jobq: - return - _jobq.dumpoutput() - - - -def job_list(ip): - keys = ip.db.keys('tasks/*') - ents = [ip.db[k] for k in keys] - return ents - -def magic_tasks(self,line): - """ Show a list of tasks. - - A 'task' is a process that has been started in IPython when 'jobctrl' extension is enabled. - Tasks can be killed with %kill. - - '%tasks clear' clears the task list (from stale tasks) - """ - ip = self.getapi() - if line.strip() == 'clear': - for k in ip.db.keys('tasks/*'): - print "Clearing",ip.db[k] - del ip.db[k] - return - - ents = job_list(ip) - if not ents: - print "No tasks running" - for pid,cmd,cwd,t in ents: - dur = int(time.time()-t) - print "%d: '%s' (%s) %d:%02d" % (pid,cmd,cwd, dur / 60,dur%60) - -def magic_kill(self,line): - """ Kill a task - - Without args, either kill one task (if only one running) or show list (if many) - With arg, assume it's the process id. - - %kill is typically (much) more powerful than trying to terminate a process with ctrl+C. - """ - ip = self.getapi() - jobs = job_list(ip) - - if not line.strip(): - if len(jobs) == 1: - kill_process(jobs[0][0]) - else: - magic_tasks(self,line) - return - - try: - pid = int(line) - kill_process(pid) - except ValueError: - magic_tasks(self,line) - -if sys.platform == 'win32': - shell_internal_commands = 'break chcp cls copy ctty date del erase dir md mkdir path prompt rd rmdir start time type ver vol'.split() - PopenExc = WindowsError -else: - # todo linux commands - shell_internal_commands = [] - PopenExc = OSError - - -def jobctrl_shellcmd(ip,cmd): - """ os.system replacement that stores process info to db['tasks/t1234'] """ - cmd = cmd.strip() - cmdname = cmd.split(None,1)[0] - if cmdname in shell_internal_commands or '|' in cmd or '>' in cmd or '<' in cmd: - use_shell = True - else: - use_shell = False - - jobentry = None - try: - try: - p = Popen(cmd,shell = use_shell) - except PopenExc : - if use_shell: - # try with os.system - os.system(cmd) - return - else: - # have to go via shell, sucks - p = Popen(cmd,shell = True) - - jobentry = 'tasks/t' + str(p.pid) - ip.db[jobentry] = (p.pid,cmd,os.getcwdu(),time.time()) - p.communicate() - - finally: - if jobentry: - del ip.db[jobentry] - - -def install(): - global ip - ip = ipapi.get() - # needed to make startjob visible as _ip.startjob('blah') - ip.startjob = startjob - ip.set_hook('input_prefilter', jobctrl_prefilter_f) - ip.set_hook('shell_hook', jobctrl_shellcmd) - ip.define_magic('kill',magic_kill) - ip.define_magic('tasks',magic_tasks) - ip.define_magic('jobqueue',jobqueue_f) - ip.set_hook('pre_prompt_hook', jobq_output_hook) -install() diff --git a/IPython/quarantine/ledit.py b/IPython/quarantine/ledit.py deleted file mode 100644 index e5204b9..0000000 --- a/IPython/quarantine/ledit.py +++ /dev/null @@ -1,98 +0,0 @@ -""" Fun magic line editor for ipython - -Use this to easily edit lists of strings gradually without crafting long -list comprehensions. - -'l' is the magic variable name for every line (array element). Save the current -result (or more exactly, retrieve the last ipython computation result into -%led work area) by running '%led s'. Just run '%led' to show the current work -area data. - -Example use: - -[ipython]|25> setups = !ls *setup*.py - == -['eggsetup.py', 'setup.py', 'setup_bdist_egg.py'] -[ipython]|26> setups - <26> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py'] -[ipython]|27> %led s -Data set from last result (_) - <27> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py'] -[ipython]|28> %led upper -cmd translated => l.upper() - <28> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY'] -[ipython]|29> %led -Magic line editor (for lists of strings) -current data is: -['eggsetup.py', 'setup.py', 'setup_bdist_egg.py'] -[ipython]|30> %led upper -cmd translated => l.upper() - <30> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY'] -[ipython]|31> %led s -Data set from last result (_) - <31> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY'] -[ipython]|32> %led "n:" + l - <32> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY'] -[ipython]|33> %led s -Data set from last result (_) - <33> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY'] -[ipython]|34> %led l. -l.__add__ l.__gt__ l.__reduce_ex__ l.endswith l.join l.rstrip -l.__class__ l.__hash__ l.__repr__ l.expandtabs l.ljust l.split - -... (completions for string variable shown ) ... - -""" -from IPython.core import ipapi -import pprint -ip = ipapi.get() - -curdata = [] - -def line_edit_f(self, cmd ): - global curdata - - if not cmd: - - print "Magic line editor (for lists of strings)" - if curdata: - print "current data is:" - pprint.pprint(curdata) - else: - print "No current data, you should set it by running '%led s'" - print "When you have your data in _ (result of last computation)." - return - - if cmd == 's': - curdata = ip.ev('_') - print "Data set from last result (_)" - newlines = curdata - - else: - # simple method call, e.g. upper - if cmd.isalpha(): - cmd = 'l.' + cmd + '()' - print "cmd translated =>",cmd - - newlines = [] - for l in curdata: - try: - l2 = eval(cmd) - except Exception as e: - print "Dropping exception",e,"on line:",l - continue - newlines.append(l2) - - - return newlines - -def line_edit_complete_f(self,event): - """ Show all string methods in completions """ - if event.symbol.startswith('l.'): - return ['l.' + func for func in dir('')] - - return dir('') + ['l.' + func for func in dir('')] - -ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led') - -ip.define_magic('led', line_edit_f) diff --git a/IPython/quarantine/tests/__init__.py b/IPython/quarantine/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/quarantine/tests/__init__.py +++ /dev/null diff --git a/IPython/quarantine/win32clip.py b/IPython/quarantine/win32clip.py deleted file mode 100644 index 121559a..0000000 --- a/IPython/quarantine/win32clip.py +++ /dev/null @@ -1,45 +0,0 @@ -from IPython.core import ipapi - -ip = ipapi.get() - -def clip_f( self, parameter_s = '' ): - """Save a set of lines to the clipboard. - - Usage:\\ - %clip n1-n2 n3-n4 ... n5 .. n6 ... - - This function uses the same syntax as %macro for line extraction, but - instead of creating a macro it saves the resulting string to the - clipboard. - - When used without arguments, this returns the text contents of the clipboard. - E.g. - - mytext = %clip - - """ - - import win32clipboard as cl - import win32con - args = parameter_s.split() - cl.OpenClipboard() - if len( args ) == 0: - data = cl.GetClipboardData( win32con.CF_TEXT ) - cl.CloseClipboard() - return data - api = self.getapi() - - if parameter_s.lstrip().startswith('='): - rest = parameter_s[parameter_s.index('=')+1:].strip() - val = str(api.ev(rest)) - else: - ranges = args[0:] - val = ''.join( self.extract_input_slices( ranges ) ) - - cl.EmptyClipboard() - cl.SetClipboardText( val ) - cl.CloseClipboard() - print 'The following text was written to the clipboard' - print val - -ip.define_magic( "clip", clip_f )