Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@
- `%%with_temp_dir` -- Run Python code in a temporary directory and
clean up it after the execution.

# Installation

Install using pip:

```
pip install ipython-tempmagic # PyPI published version
```

or

```
pip install git+https://github.com/Lightslayer/ipython-tempmagic # development version
```

For older Jupyter versions (< 5.0):

```text
%install_ext https://raw.github.com/tkf/ipython-tempmagic/master/tempmagic.py
```
51 changes: 51 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import io
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the relevant file
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()

install_requires = [
'jupyter>=1.0.0',
]

setup(
name='ipython-tempmagic',
version='0.0.1',
description='Temporary file magic IPython',
long_description=long_description,
url='https://github.com/tkf/ipython-tempmagic',

# Author details
author='Takafumi Arakaki',
author_email='aka.tkf@gmail.com',
maintainer='Liam Deacon',
maintainer_email='liam.m.deacon@gmail.com',

# Choose your license
license='',

# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Topic :: Text Processing :: Markup :: HTML',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],

# What does your project relate to?
keywords='ipython jupyter notebook tempfile tempdir',

packages={'tempmagic':''},
py_modules=['tempmagic.py'],
install_requires=install_requires,
)
1 change: 1 addition & 0 deletions tempmagic/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from tempmagic import *
Binary file added tempmagic/__init__.pyc
Binary file not shown.
86 changes: 86 additions & 0 deletions tempmagic/tempmagic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import os
import atexit
import contextlib

from IPython.core.magic import Magics, magics_class, line_magic, cell_magic
from IPython.core.magic_arguments import (argument, magic_arguments,
parse_argstring)
from IPython.utils.tempdir import TemporaryDirectory


@contextlib.contextmanager
def chcwd(path):
cwd = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(cwd)


@magics_class
class TempMagic(Magics):

def __init__(self, *args, **kwds):
super(TempMagic, self).__init__(*args, **kwds)
self._temp_dirs = []
atexit.register(self.cleanup_all)

def cleanup_all(self):
for td in self._temp_dirs:
try:
td.cleanup()
except:
pass
self._temp_dirs[:] = []

@staticmethod
def _filter_none_values(*args, **kwds):
return dict(
(k, v) for (k, v) in dict(*args, **kwds).items()
if v is not None)

@magic_arguments()
@argument('--suffix', '-s', default=None)
@argument('--prefix', '-p', default=None)
@argument('--directory', '-d', default=None)
@line_magic
def cdtemp(self, parameter_s=''):
"""
Make temporary directory and change the current to there.

The temporary directory made will be removed when the current
IPython process terminates.

"""
args = parse_argstring(self.cdtemp, parameter_s)
kwds = self._filter_none_values(vars(args))
td = TemporaryDirectory(**kwds)
self._temp_dirs.append(td)
os.chdir(td.name)
return td.name

@magic_arguments()
@argument('--suffix', '-s', default=None)
@argument('--prefix', '-p', default=None)
@argument('--directory', '-d', default=None)
@cell_magic
def with_temp_dir(self, line, cell):
"""
Execute code in a temporary directory.
"""
args = parse_argstring(self.with_temp_dir, line)
kwds = self._filter_none_values(vars(args))
with TemporaryDirectory(**kwds) as path:
with chcwd(path):
self.shell.run_cell(cell)


def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(TempMagic)
_loaded = True

_loaded = False
Binary file added tempmagic/tempmagic.pyc
Binary file not shown.