Importing scripts into a notebook

You might only want to include the necessary bits of code for your notebook that can be used in a presentation to communicate the results of your analysis. All helper functions, classes, and visualization code snippets for example, do not have to be included in the notebook. Instead you can add this code to a script which can be shared by all of the notebooks sharing the same runtime.

To import a script from your local machine to a notebook in Watson Studio and write to the script from the notebook, use one of the following options:

  • Copy the code from your local script file into a notebook cell.

    • For Python:

      At the beginning of this cell, add %%writefile to save the code as a Python file to your working directory. Notebooks that use the same runtime can also import this file.

      The advantage of this method is that the code is available in your notebook, and you can edit and save it as a new Python script at any time.

    • For R:

      If you want to save code in a notebook as an R script to the working directory, you can use the writeLines(myfile.R) function.

  • Save your local script file in Cloud Object Storage and then make the file available to the runtime by adding it to the runtime’s local file system. This is only supported for Python.

    1. Click the Add Data icon (Shows the Add Data icon), and then browse the script file or drag it into your notebook sidebar. The script file is added to Cloud Object Storage bucket associated with your project.
    2. Make the script file available to the Python runtime by adding the script to the runtime’s local file system:

      a. First read the script contents from Cloud Object Storage to a StreamingBody object by clicking an empty cell in your notebook and then selecting Insert StreamingBody object from the menu next the script file you added in the notebook sidebar.
      Insert StreamingBody object to notebook
      b. Write the contents of the StreamingBody object to a file in the local runtime`s file system:

         f = open('<myScript>.py', 'wb')

      This opens a file with write access and calls the write method to write to the file.

      c. Import the script:

         import <myScript>

To import the classes to access the methods in a script in your notebook, use the following command:

  • For Python:

    from <python file name> import <class name>
  • For R:

    ## available in base R

    To source an R script from the web:

    source_url("<insert URL here>")
    ## available in devtools