<s> from metakernel import Magic , option <EOL> import urllib <EOL> try : <EOL> import urlparse <EOL> except ImportError : <EOL> from urllib import parse as urlparse <EOL> import os <EOL> try : <EOL> urllib . URLopener <EOL> def download ( url , filename ) : <EOL> opener = urllib . URLopener ( ) <EOL> opener . retrieve ( url , filename ) <EOL> except : <EOL> import urllib . request <EOL> def download ( url , filename ) : <EOL> g = urllib . request . urlopen ( url ) <EOL> with open ( filename , '<STR_LIT:wb>' ) as f : <EOL> f . write ( g . read ( ) ) <EOL> class DownloadMagic ( Magic ) : <EOL> @ option ( <EOL> '<STR_LIT>' , '<STR_LIT>' , action = '<STR_LIT:store>' , default = None , <EOL> help = '<STR_LIT>' <EOL> ) <EOL> def line_download ( self , url , filename = None ) : <EOL> """<STR_LIT>""" <EOL> if filename is None : <EOL> parts = urlparse . urlsplit ( url ) <EOL> path = parts [ <NUM_LIT:2> ] <EOL> filename = os . path . basename ( path ) <EOL> if filename != '<STR_LIT>' : <EOL> basename , extname = os . path . splitext ( filename ) <EOL> if extname == '<STR_LIT>' : <EOL> filename += "<STR_LIT>" <EOL> filename = filename . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> filename = filename . replace ( "<STR_LIT>" , "<STR_LIT:_>" ) <EOL> else : <EOL> filename = "<STR_LIT>" <EOL> try : <EOL> download ( url , filename ) <EOL> self . kernel . Print ( "<STR_LIT>" % filename ) <EOL> except Exception as e : <EOL> self . kernel . Error ( str ( e ) ) <EOL> def register_magics ( kernel ) : <EOL> kernel . register_magics ( DownloadMagic ) <EOL> def register_ipython_magics ( ) : <EOL> from metakernel import IPythonKernel <EOL> from IPython . core . magic import register_line_magic <EOL> kernel = IPythonKernel ( ) <EOL> magic = DownloadMagic ( kernel ) <EOL> kernel . line_magics [ "<STR_LIT>" ] = magic <EOL> @ register_line_magic <EOL> def download ( line ) : <EOL> kernel . call_magic ( "<STR_LIT>" + line ) </s>
