Retrieving files from remote IPython notebook server?

12,853

Solution 1

You can use FileLink and FileLinks that are built-in:

from IPython.display import FileLink, FileLinks
FileLinks('.') #lists all downloadable files on server

The code above generates:

./
some_python_file.py
some_xml_file.xml
some_ipynb_file.ipynb

The three items above are links that you can click to download.

Click here for an example from ipython.org

Solution 2

Unfortunately due to edge case reasons, FileLink doesn't work for files outside the Jupyter directory. You can however get around this by creating a link to the file first:

os.symlink( file_name, "tmp.txt" )
display( FileLink( "tmp.txt" ) )

In reality the workaround above leaves the link on disk. It also assumes everything has a "txt" extension. We probably want to clean up previous links to avoid cluttering the directory, and not rename the downloaded file. Here is a solution that persists only one link at at time and retains the base name:

def download_file( file_name : str ) -> None:
    import os
    from IPython.display import display, FileLink
    
    base_name : str = os.path.basename( file_name )
    k_info_file : str = ".download_file_info.txt"
    
    # Remove previous link
    if os.path.isfile( k_info_file ):
        with open( k_info_file, "r" ) as fin:
            previous_file = fin.read()
        
        if os.path.isfile( previous_file ):
            print( "Removing previous file link." )
            os.remove( previous_file )
    
    # Remember current link
    with open( k_info_file, "w" ) as fout:
        fout.write( base_name )
    
    # Create the link
    assert not os.path.isfile( base_name ), "Name in use."
    os.symlink( file_name, base_name )
    
    # Return the link
    display( FileLink( base_name ) )
Share:
12,853

Related videos on Youtube

user1234310
Author by

user1234310

Updated on June 22, 2022

Comments

  • user1234310
    user1234310 almost 2 years

    If I don't want to give out SSH access to users of my remote IPython notebook server. Is there a way to let users browse non .ipynb files and download them?

  • Jason
    Jason over 6 years
    How to download all of them with their original folder hierarchy without clicking into every single item?