Import 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.

    1. Click the Add Data icon (Shows the Add Data icon), and then browse the script file or drag it into your notebook sidebar.
    2. Click in an empty code cell in your notebook and then click the Insert to code link below the file. Take the returned string, and write to a file in the file system that comes with the runtime session.

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