Как открыть jupiter notebook в браузере

от admin

Running the Notebook#

Start the notebook server from the command line :

You should see the notebook open in your browser.

Starting the Notebook Server#

After you have installed the Jupyter Notebook on your computer, you are ready to run the notebook server. You can start the notebook server from the command line (using Terminal on Mac/Linux, Command Prompt on Windows) by running:

This will print some information about the notebook server in your terminal, including the URL of the web application (by default, http://localhost:8888 ):

It will then open your default web browser to this URL.

When the notebook opens in your browser, you will see the Notebook Dashboard , which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. Most of the time, you will wish to start a notebook server in the highest level directory containing notebooks. Often this will be your home directory.

Notebook Dashboard

Introducing the Notebook Server’s Command Line Options#

How do I open a specific Notebook?#

The following code should open the given notebook in the currently running notebook server, starting one if necessary.

How do I start the Notebook using a custom IP or port?#

By default, the notebook server starts on port 8888. If port 8888 is unavailable or in use, the notebook server searches the next available port. You may also specify a port manually. In this example, we set the server’s port to 9999:

How do I start the Notebook server without opening a browser?#

Start notebook server without opening a web browser:

How do I get help about Notebook server options?#

The notebook server provides help messages for other command line arguments using the —help flag:

Detailed information about command line arguments, configuration, and usage.

Using a command-line interface#

Notebooks can be executed from your terminal using the run subcommand. It expects notebook paths as input arguments and accepts optional flags to modify the default behavior.

Running a notebook is this easy.

You can pass more than one notebook as well.

By default, notebook errors will be raised and printed into the terminal. You can suppress them by passing the —allow-errors flag.

For more sophisticated execution options, consider the papermill library.

The Jupyter Notebook

The notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results. The Jupyter notebook combines two components:

A web application: a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output.

Notebook documents: a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects.

See the installation guide on how to install the notebook and its dependencies.

Main features of the web application

In-browser editing for code, with automatic syntax highlighting, indentation, and tab completion/introspection.

The ability to execute code from the browser, with the results of computations attached to the code which generated them.

Displaying the result of computation using rich media representations, such as HTML, LaTeX, PNG, SVG, etc. For example, publication-quality figures rendered by the matplotlib library, can be included inline.

In-browser editing for rich text using the Markdown markup language, which can provide commentary for the code, is not limited to plain text.

The ability to easily include mathematical notation within markdown cells using LaTeX, and rendered natively by MathJax.

Notebook documents

Notebook documents contains the inputs and outputs of a interactive session as well as additional text that accompanies the code but is not meant for execution. In this way, notebook files can serve as a complete computational record of a session, interleaving executable code with explanatory text, mathematics, and rich representations of resulting objects. These documents are internally JSON files and are saved with the .ipynb extension. Since JSON is a plain text format, they can be version-controlled and shared with colleagues.

Notebooks may be exported to a range of static formats, including HTML (for example, for blog posts), reStructuredText, LaTeX, PDF, and slide shows, via the nbconvert command.

Furthermore, any .ipynb notebook document available from a public URL can be shared via the Jupyter Notebook Viewer <nbviewer>. This service loads the notebook document from the URL and renders it as a static web page. The results may thus be shared with a colleague, or as a public blog post, without other users needing to install the Jupyter notebook themselves. In effect, nbviewer is simply nbconvert as a web service, so you can do your own static conversions with nbconvert, without relying on nbviewer.

Notebooks and privacy

Because you use Jupyter in a web browser, some people are understandably concerned about using it with sensitive data. However, if you followed the standard install instructions, Jupyter is actually running on your own computer. If the URL in the address bar starts with http://localhost: or http://127.0.0.1: , it’s your computer acting as the server. Jupyter doesn’t send your data anywhere else—and as it’s open source, other people can check that we’re being honest about this.

You can also use Jupyter remotely: your company or university might run the server for you, for instance. If you want to work with sensitive data in those cases, talk to your IT or data protection staff about it.

We aim to ensure that other pages in your browser or other users on the same computer can’t access your notebook server. See Security in the Jupyter notebook server for more about this.

Starting the notebook server

You can start running a notebook server from the command line using the following command:

This will print some information about the notebook server in your console, and open a web browser to the URL of the web application (by default, http://127.0.0.1:8888 ).

The landing page of the Jupyter notebook web application, the dashboard, shows the notebooks currently available in the notebook directory (by default, the directory from which the notebook server was started).

You can create new notebooks from the dashboard with the New Notebook button, or open existing ones by clicking on their name. You can also drag and drop .ipynb notebooks and standard .py Python source code files into the notebook list area.

When starting a notebook server from the command line, you can also open a particular notebook directly, bypassing the dashboard, with jupyter notebook my_notebook.ipynb . The .ipynb extension is assumed if no extension is given.

When you are inside an open notebook, the File | Open… menu option will open the dashboard in a new browser tab, to allow you to open another notebook from the notebook directory or to create a new notebook.

You can start more than one notebook server at the same time, if you want to work on notebooks in different directories. By default the first notebook server starts on port 8888, and later notebook servers search for ports near that one. You can also manually specify the port with the —port option.

Creating a new notebook document

A new notebook may be created at any time, either from the dashboard, or using the File ‣ New menu option from within an active notebook. The new notebook is created within the same directory and will open in a new browser tab. It will also be reflected as a new entry in the notebook list on the dashboard.

Opening notebooks

An open notebook has exactly one interactive session connected to a kernel, which will execute code sent by the user and communicate back results. This kernel remains active if the web browser window is closed, and reopening the same notebook from the dashboard will reconnect the web application to the same kernel. In the dashboard, notebooks with an active kernel have a Shutdown button next to them, whereas notebooks without an active kernel have a Delete button in its place.

Other clients may connect to the same kernel. When each kernel is started, the notebook server prints to the terminal a message like this:

This long string is the kernel’s ID which is sufficient for getting the information necessary to connect to the kernel. If the notebook uses the IPython kernel, you can also see this connection data by running the %connect_info magic , which will print the same ID information along with other details.

You can then, for example, manually start a Qt console connected to the same kernel from the command line, by passing a portion of the ID:

Without an ID, —existing will connect to the most recently started kernel.

With the IPython kernel, you can also run the %qtconsole magic in the notebook to open a Qt console connected to the same kernel.

Notebook user interface

When you create a new notebook document, you will be presented with the notebook name, a menu bar, a toolbar and an empty code cell.

_images/blank-notebook-ui.png

Notebook name: The name displayed at the top of the page, next to the Jupyter logo, reflects the name of the .ipynb file. Clicking on the notebook name brings up a dialog which allows you to rename it. Thus, renaming a notebook from “Untitled0” to “My first notebook” in the browser, renames the Untitled0.ipynb file to My first notebook.ipynb .

Menu bar: The menu bar presents different options that may be used to manipulate the way the notebook functions.

Toolbar: The tool bar gives a quick way of performing the most-used operations within the notebook, by clicking on an icon.

Code cell: the default type of cell; read on for an explanation of cells.

Structure of a notebook document

The notebook consists of a sequence of cells. A cell is a multiline text input field, and its contents can be executed by using Shift — Enter , or by clicking either the “Play” button the toolbar, or Cell , Run in the menu bar. The execution behavior of a cell is determined by the cell’s type. There are three types of cells: code cells, markdown cells, and raw cells. Every cell starts off being a code cell, but its type can be changed by using a drop-down on the toolbar (which will be “Code”, initially), or via keyboard shortcuts .

For more information on the different things you can do in a notebook, see the collection of examples.

Code cells

A code cell allows you to edit and write new code, with full syntax highlighting and tab completion. The programming language you use depends on the kernel, and the default kernel (IPython) runs Python code.

When a code cell is executed, code that it contains is sent to the kernel associated with the notebook. The results that are returned from this computation are then displayed in the notebook as the cell’s output. The output is not limited to text, with many other possible forms of output are also possible, including matplotlib figures and HTML tables (as used, for example, in the pandas data analysis package). This is known as IPython’s rich display capability.

Markdown cells

You can document the computational process in a literate way, alternating descriptive text with code, using rich text. In IPython this is accomplished by marking up text with the Markdown language. The corresponding cells are called Markdown cells. The Markdown language provides a simple way to perform this text markup, that is, to specify which parts of the text should be emphasized (italics), bold, form lists, etc.

If you want to provide structure for your document, you can use markdown headings. Markdown headings consist of 1 to 6 hash # signs # followed by a space and the title of your section. The markdown heading will be converted to a clickable link for a section of the notebook. It is also used as a hint when exporting to other document formats, like PDF.

When a Markdown cell is executed, the Markdown code is converted into the corresponding formatted rich text. Markdown allows arbitrary HTML code for formatting.

Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $. $ for inline mathematics and $$. $$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality

Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin. \end , and \begin. \end . New LaTeX macros may be defined using standard methods, such as \newcommand , by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.

Raw cells

Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, you can type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

Basic workflow

The normal workflow in a notebook is, then, quite similar to a standard IPython session, with the difference that you can edit cells in-place multiple times until you obtain the desired results, rather than having to rerun separate scripts with the %run magic command.

Typically, you will work on a computational problem in pieces, organizing related ideas into cells and moving forward once previous parts work correctly. This is much more convenient for interactive exploration than breaking up a computation into scripts that must be executed together, as was previously necessary, especially if parts of them take a long time to run.

To interrupt a calculation which is taking too long, use the Kernel , Interrupt menu option, or the i,i keyboard shortcut. Similarly, to restart the whole computational process, use the Kernel , Restart menu option or 0,0 shortcut.

A notebook may be downloaded as a .ipynb file or converted to a number of other formats using the menu option File , Download as .

Keyboard shortcuts

All actions in the notebook can be performed with the mouse, but keyboard shortcuts are also available for the most common ones. The essential shortcuts to remember are the following:

    Shift — Enter : run cell

Execute the current cell, show any output, and jump to the next cell below. If Shift — Enter is invoked on the last cell, it makes a new cell below. This is equivalent to clicking the Cell , Run menu item, or the Play button in the toolbar.

In command mode, you can navigate around the notebook using keyboard shortcuts.

In edit mode, you can edit text in cells.

For the full list of available shortcuts, click Help , Keyboard Shortcuts in the notebook menus.

Plotting

One major feature of the Jupyter notebook is the ability to display plots that are the output of running code cells. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality. Specific plotting library integration is a feature of the kernel.

Installing kernels

For information on how to install a Python kernel, refer to the IPython install page.

The Jupyter wiki has a long list of Kernels for other languages. They usually come with instructions on how to make the kernel available in the notebook.

Trusting Notebooks

To prevent untrusted code from executing on users’ behalf when notebooks open, we store a signature of each trusted notebook. The notebook server verifies this signature when a notebook is opened. If no matching signature is found, Javascript and HTML output will not be displayed until they are regenerated by re-executing the cells.

Any notebook that you have fully executed yourself will be considered trusted, and its HTML and Javascript output will be displayed on load.

If you need to see HTML or Javascript output without re-executing, and you are sure the notebook is not malicious, you can tell Jupyter to trust it at the command-line with:

See Security in notebook documents for more details about the trust mechanism.

Browser Compatibility

The Jupyter Notebook aims to support the latest versions of these browsers:

Up to date versions of Opera and Edge may also work, but if they don’t, please use one of the supported browsers.

Using Safari with HTTPS and an untrusted certificate is known to not work (websockets will fail).

Name already in use

notebook / docs / source / notebook.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The Jupyter Notebook

The notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results. The Jupyter notebook combines two components:

A web application: a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output.

Notebook documents: a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects.

Main features of the web application

  • In-browser editing for code, with automatic syntax highlighting, indentation, and tab completion/introspection.
  • The ability to execute code from the browser, with the results of computations attached to the code which generated them.
  • Displaying the result of computation using rich media representations, such as HTML, LaTeX, PNG, SVG, etc. For example, publication-quality figures rendered by the matplotlib_ library, can be included inline.
  • In-browser editing for rich text using the Markdown_ markup language, which can provide commentary for the code, is not limited to plain text.
  • The ability to easily include mathematical notation within markdown cells using LaTeX, and rendered natively by MathJax.

Notebook documents contains the inputs and outputs of a interactive session as well as additional text that accompanies the code but is not meant for execution. In this way, notebook files can serve as a complete computational record of a session, interleaving executable code with explanatory text, mathematics, and rich representations of resulting objects. These documents are internally JSON files and are saved with the .ipynb extension. Since JSON is a plain text format, they can be version-controlled and shared with colleagues.

Notebooks may be exported to a range of static formats, including HTML (for example, for blog posts), reStructuredText, LaTeX, PDF, and slide shows, via the nbconvert_ command.

Furthermore, any .ipynb notebook document available from a public URL can be shared via the Jupyter Notebook Viewer <nbviewer>. This service loads the notebook document from the URL and renders it as a static web page. The results may thus be shared with a colleague, or as a public blog post, without other users needing to install the Jupyter notebook themselves. In effect, nbviewer is simply nbconvert_ as a web service, so you can do your own static conversions with nbconvert, without relying on nbviewer.

Notebooks and privacy

Because you use Jupyter in a web browser, some people are understandably concerned about using it with sensitive data. However, if you followed the standard install instructions, Jupyter is actually running on your own computer. If the URL in the address bar starts with http://localhost: or http://127.0.0.1: , it’s your computer acting as the server. Jupyter doesn’t send your data anywhere else—and as it’s open source, other people can check that we’re being honest about this.

You can also use Jupyter remotely: your company or university might run the server for you, for instance. If you want to work with sensitive data in those cases, talk to your IT or data protection staff about it.

We aim to ensure that other pages in your browser or other users on the same computer can’t access your notebook server. See the security documentation for more about this.

Starting the notebook server

You can start running a notebook server from the command line using the following command:

This will print some information about the notebook server in your console, and open a web browser to the URL of the web application (by default, http://127.0.0.1:8888 ).

The landing page of the Jupyter notebook web application, the dashboard, shows the notebooks currently available in the notebook directory (by default, the directory from which the notebook server was started).

You can create new notebooks from the dashboard with the New Notebook button, or open existing ones by clicking on their name. You can also drag and drop .ipynb notebooks and standard .py Python source code files into the notebook list area.

When starting a notebook server from the command line, you can also open a particular notebook directly, bypassing the dashboard, with jupyter notebook my_notebook.ipynb . The .ipynb extension is assumed if no extension is given.

When you are inside an open notebook, the File | Open. menu option will open the dashboard in a new browser tab, to allow you to open another notebook from the notebook directory or to create a new notebook.

You can start more than one notebook server at the same time, if you want to work on notebooks in different directories. By default the first notebook server starts on port 8888, and later notebook servers search for ports near that one. You can also manually specify the port with the —port option.

Creating a new notebook document

A new notebook may be created at any time, either from the dashboard, or using the :menuselection:`File —> New` menu option from within an active notebook. The new notebook is created within the same directory and will open in a new browser tab. It will also be reflected as a new entry in the notebook list on the dashboard.

An open notebook has exactly one interactive session connected to a kernel, which will execute code sent by the user and communicate back results. This kernel remains active if the web browser window is closed, and reopening the same notebook from the dashboard will reconnect the web application to the same kernel. In the dashboard, notebooks with an active kernel have a Shutdown button next to them, whereas notebooks without an active kernel have a Delete button in its place.

Other clients may connect to the same kernel. When each kernel is started, the notebook server prints to the terminal a message like this:

This long string is the kernel’s ID which is sufficient for getting the information necessary to connect to the kernel. If the notebook uses the IPython kernel, you can also see this connection data by running the %connect_info :ref:`magic <magics_explained>` , which will print the same ID information along with other details.

You can then, for example, manually start a Qt console connected to the same kernel from the command line, by passing a portion of the ID:

Without an ID, —existing will connect to the most recently started kernel.

With the IPython kernel, you can also run the %qtconsole :ref:`magic <magics_explained>` in the notebook to open a Qt console connected to the same kernel.

Notebook user interface

When you create a new notebook document, you will be presented with the notebook name, a menu bar, a toolbar and an empty code cell.

./_static/images/blank-notebook-ui.png

Notebook name: The name displayed at the top of the page, next to the Jupyter logo, reflects the name of the .ipynb file. Clicking on the notebook name brings up a dialog which allows you to rename it. Thus, renaming a notebook from «Untitled0» to «My first notebook» in the browser, renames the Untitled0.ipynb file to My first notebook.ipynb .

Menu bar: The menu bar presents different options that may be used to manipulate the way the notebook functions.

Toolbar: The tool bar gives a quick way of performing the most-used operations within the notebook, by clicking on an icon.

Code cell: the default type of cell; read on for an explanation of cells.

Structure of a notebook document

The notebook consists of a sequence of cells. A cell is a multiline text input field, and its contents can be executed by using Shift-Enter , or by clicking either the «Play» button the toolbar, or :guilabel:`Cell` , :guilabel:`Run` in the menu bar. The execution behavior of a cell is determined by the cell’s type. There are three types of cells: code cells, markdown cells, and raw cells. Every cell starts off being a code cell, but its type can be changed by using a drop-down on the toolbar (which will be «Code», initially), or via :ref:`keyboard shortcuts <keyboard-shortcuts>` .

For more information on the different things you can do in a notebook, see the collection of examples.

A code cell allows you to edit and write new code, with full syntax highlighting and tab completion. The programming language you use depends on the kernel, and the default kernel (IPython) runs Python code.

When a code cell is executed, code that it contains is sent to the kernel associated with the notebook. The results that are returned from this computation are then displayed in the notebook as the cell’s output. The output is not limited to text, with many other possible forms of output are also possible, including matplotlib figures and HTML tables (as used, for example, in the pandas data analysis package). This is known as IPython’s rich display capability.

You can document the computational process in a literate way, alternating descriptive text with code, using rich text. In IPython this is accomplished by marking up text with the Markdown language. The corresponding cells are called Markdown cells. The Markdown language provides a simple way to perform this text markup, that is, to specify which parts of the text should be emphasized (italics), bold, form lists, etc.

If you want to provide structure for your document, you can use markdown headings. Markdown headings consist of 1 to 6 hash # signs # followed by a space and the title of your section. The markdown heading will be converted to a clickable link for a section of the notebook. It is also used as a hint when exporting to other document formats, like PDF.

When a Markdown cell is executed, the Markdown code is converted into the corresponding formatted rich text. Markdown allows arbitrary HTML code for formatting.

Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $. $ for inline mathematics and $$. $$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality

Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin. \end , and \begin. \end . New LaTeX macros may be defined using standard methods, such as \newcommand , by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.

Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert_ , raw cells arrive in the destination format unmodified. For example, you can type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

The normal workflow in a notebook is, then, quite similar to a standard IPython session, with the difference that you can edit cells in-place multiple times until you obtain the desired results, rather than having to rerun separate scripts with the %run magic command.

Typically, you will work on a computational problem in pieces, organizing related ideas into cells and moving forward once previous parts work correctly. This is much more convenient for interactive exploration than breaking up a computation into scripts that must be executed together, as was previously necessary, especially if parts of them take a long time to run.

To interrupt a calculation which is taking too long, use the :guilabel:`Kernel` , :guilabel:`Interrupt` menu option, or the i,i keyboard shortcut. Similarly, to restart the whole computational process, use the :guilabel:`Kernel` , :guilabel:`Restart` menu option or 0,0 shortcut.

A notebook may be downloaded as a .ipynb file or converted to a number of other formats using the menu option :guilabel:`File` , :guilabel:`Download as` .

All actions in the notebook can be performed with the mouse, but keyboard shortcuts are also available for the most common ones. The essential shortcuts to remember are the following:

  • Shift-Enter : run cell Execute the current cell, show any output, and jump to the next cell below. If Shift-Enter is invoked on the last cell, it makes a new cell below. This is equivalent to clicking the :guilabel:`Cell` , :guilabel:`Run` menu item, or the Play button in the toolbar.
  • Esc : Command mode In command mode, you can navigate around the notebook using keyboard shortcuts.
  • Enter : Edit mode In edit mode, you can edit text in cells.

For the full list of available shortcuts, click :guilabel:`Help` , :guilabel:`Keyboard Shortcuts` in the notebook menus.

One major feature of the Jupyter notebook is the ability to display plots that are the output of running code cells. The IPython kernel is designed to work seamlessly with the matplotlib_ plotting library to provide this functionality. Specific plotting library integration is a feature of the kernel.

For information on how to install a Python kernel, refer to the IPython install page.

The Jupyter wiki has a long list of Kernels for other languages. They usually come with instructions on how to make the kernel available in the notebook.

To prevent untrusted code from executing on users’ behalf when notebooks open, we store a signature of each trusted notebook. The notebook server verifies this signature when a notebook is opened. If no matching signature is found, Javascript and HTML output will not be displayed until they are regenerated by re-executing the cells.

Any notebook that you have fully executed yourself will be considered trusted, and its HTML and Javascript output will be displayed on load.

If you need to see HTML or Javascript output without re-executing, and you are sure the notebook is not malicious, you can tell Jupyter to trust it at the command-line with:

See the security documentation for more details about the trust mechanism.

The Jupyter Notebook aims to support the latest versions of these browsers:

  • Chrome
  • Safari
  • Firefox

Up to date versions of Opera and Edge may also work, but if they don’t, please use one of the supported browsers.

Using Safari with HTTPS and an untrusted certificate is known to not work (websockets will fail).

Как настроить Jupyter Notebook для Python 3

Обложка: Как настроить Jupyter Notebook для Python 3

Jupyter Notebook — это командная оболочка для интерактивных вычислений. Этот инструмент может использоваться не только с Python, но и другими языками программирования: Julia, R, Haskell и Ruby. Он часто используется для работы с данными, статистическим моделированием и машинным обучением.

В статье мы рассмотрим, как настроить Jupyter Notebook для локального запуска или запуска на сервере под управлением Ubuntu 16.04. Этот инструмент поможет создавать файлы (notebooks), которые содержат не только компьютерный код, но и другие элементы (заметки, уравнения, диаграммы, ссылки и т.д.), которыми можно потом поделиться с заказчиками или друзьями.

После прочтения этой статьи вы будете знать, как запускать код Python 3 при помощи Jupyter Notebook локально или на удалённом сервере.

Требования

Нам понадобится среда программирования для Python 3, установленная либо на локальной машине, либо на сервере Ubuntu 16.04.

Шаг 1. Установка Jupyter Notebook

Jupyter Notebook можно установить при помощи пакетного менеджера pip .

В статье будет использоваться виртуальное окружение с именем my_env . Для установки пакета для работы с виртуальным окружением введите следующую команду в терминале:

Теперь мы готовы создать виртуальное окружение. Выбираем каталог, в который все будет установлено, или создаем новый каталог с mkdir :

Как только вы переместитесь в нужную вам директорию, введите следующую команду в терминал:

По сути, pyvenv создает новый каталог, содержащий несколько элементов, которые мы можем просмотреть с помощью команды ls :

Для активации виртуального окружения вам осталось ввести последнюю команду:

Затем нужно убедиться, что pip был обновлен до последней версии:

Теперь можно установить Jupyter Notebook следующей командой:

После этой строчки кода Jupyter Notebook будет установлен в активное виртуальное окружение.

Следующий шаг предназначен для тех, кто хочет подключиться к веб-интерфейсу, используя SSH-туннелирование.

Шаг 2 (необязательный). Запуск Jupiter Notebook на сервере

Для тех, кто установил Jupyter Notebook на удаленный сервер, нужно подключаться к веб-интерфейсу через SSH-туннель. Приложение использует порт 8888 (или же 8889 ), а SSH-туннель поможет обезопасить соединение с сервером.

SSH-туннелирование с помощью Mac или Linux

Для тех, кто работает с macOS или Linux, нужно выполнить следующую команду в окне терминала:

Команда ssh создаст SSH-подключение, а флаг –L перенаправит порт локального или клиентского хоста на хост и порт уделенного сервера. То есть все, что работает на порте 8888 с серверной стороны, будет работать на порте 8888 вашей локальной машины.

При необходимости можно изменить порт 8888 на один из ваших вариантов, чтобы избежать использования порта, который уже используется другим процессом:

  • server_username — имя пользователя на сервере (например, sammy );
  • your_server_ip — это IP-адрес сервера.

Например, для имени пользователя sammy и адреса сервера 203.0.113.0 команда будет следующей:

Если после запуска команды ssh -L не появляется ошибка, можно переходить в среду программирования и запустить Jupyter Notebook:

После этого, вы получите результат содержащий URL-адрес. Введите его в окне браузера и перейдите к веб-интерфейсу Jupyter Notebook ( http://localhost:8888 ).

SSH-туннелирование с помощью Windows и Putty

Пользователи Windows могут создать туннель SSH, используя программу Putty.

Сначала нужно ввести URL-адрес сервера или IP-адрес имени хоста, как показано ниже на скриншоте:

Далее нажимаем SSH внизу левой панели, для раскрытия полного меню и нажимаем на слово Tunnels (туннели). Вводим номер локального порта, который будет использоваться для доступа к Jupyter на локальном компьютере. Выбираем порт 8000 или выше, чтобы избежать совпадения портов, используемых другими службами, и указываем назначение как localhost: 8888 , где: 8888 — это номер порта, через который работает Jupyter Notebook.

Теперь нажмите кнопку Add (добавить), и порты должны появиться в списке Forwarded ports (Переадресованные порты):

И после этого переходим по адресу http://localhost:8000 (или любым другим портом, который вы выбрали) в веб-браузере, чтобы подключиться к Jupyter Notebook, работающему на сервере.

Шаг 3. Запуск Jupyter Notebook локально

После окончания установки Jupyter Notebook можно запустить при помощи следующей команды в терминале:

В терминале выведутся логи Jupyter Notebook. При запуске инструмент использует определенный порт. Обычно это 8888 . Для проверки порта, с которым работает Jupyter Notebook, используйте команду, при помощи которой запускался Jupyter Notebook:

Если вы используете Jupyter Notebook на локальном компьютере, а не на сервере, то при открытии веб-приложения Jupyter Notebook должен открыться ваш браузер по умолчанию. Если этого не произошло, можно открыть браузер вручную и перейти к http://localhost: 8888 для подключения.

Если нужно остановить процессы Jupyter Notebook, то нажмите CTRL + C , а потом Y при появлении запроса на закрытие и ENTER для подтверждения.

Вы получите следующий результат:

Jupyter Notebook остановлен.

Шаг 4. Использование Jupyter Notebook

Пришло время начать использование Jupyter Notebook.

Теперь можно подключиться к нему с помощью веб-браузера. Jupyter Notebook — очень мощный инструмент и имеет множество функций. В этом разделе описываются некоторые основные функции, позволяющие начать работу с ним. Jupyter Notebook покажет все файлы и папки в каталоге, из которого он запущен, поэтому, когда начинается работа над проектом, обязательно нужно запускать его из каталога проекта.

Чтобы создать документ выбираем New → Python 3 в верхнем выпадающем меню:

После открытия документа можно запускать код Python в ячейке или использовать язык разметки Markdown. Чтобы изменить первую ячейку для работы с Markdown, нужно нажать в верхней панели навигации Cell → Cell Type → Markdown. Теперь можно создавать заметки с использованием Markdown и даже включать уравнения, написанные в LaTeX, помещая их между символами $$ . Например, попробуем ввести следующую команду в ячейку после включения Markdown:

Чтобы переформатировать Markdown в форматированный текст, нажимаем CTRL + ENTER и получаем следующие результаты:

Также можно использовать ячейки Markdown для написания кода. Для теста напишем небольшое уравнение и выведем результат. Нажимаем на верхнюю ячейку, нажимаем ALT+ENTER для создания ячейки под ней и вводим следующий код в новую ячейку:

Чтобы запустить код, нажимаем CTRL + ENTER и получаем следующие результаты:

Теперь у вас есть возможность импортировать модули и использовать Jupyter Notebook так же, как и в любой другой среде разработки Python!

Вывод

Поздравляем! Теперь вы можете написать воспроизводимый код Python и заметки в Markdown с помощью Jupyter Notebook. Для получения справки по использованию Jupyter Notebook нажмите Help → User Interface Tour в главном меню навигации.

Читать:
Как автоматически запускать программу от имени администратора

Related Posts