Spyder python как пользоваться
Перейти к содержимому

Spyder python как пользоваться

  • автор:

Using the Spyder IDE

Python scripts are simply text files with a .py extension; you can open them and read them — even write them — in Notepad, WordPad, Notepad++, etc. However, working with Python scripts is more easily done in an integrated development environment (IDE) as these IDEs offer tools to auto format scripts as you write them, to debug them, and even to execute Python statements or chunks of scripts interactively.

Learning Objectives

Section On completion of this lesson, you should be able to:
1. What is a Script? What is an IDE? Discuss the advantages of using an IDE over a simple text editor for writing Python scripts
2. Installing the Spyder IDE Install the Spyder IDE on a machine with ArcGIS Pro installed
3. Starting Spyder Open Spyder from the Python command prompt, in default as well as specific locations.
Describe what a Spyder project is and what a working directory is
Create a shortcut to open Spyder in a specific folder or to use a specific project
4. Navigating Spyder Navigate and use the various Spyder panes as well as customize its layout
5. Using Spyder’s Console Run Python commands from Spyder’s console
6. Using Spyder’s Editor/Debugging Create, edit, run, and debug Python scripts in Spyder’s editor

1. What is a Script? And what is an IDE?

Up to now, we wrote Python code in a Jupyter Notebook. Jupyter Notebooks have some clear benefits and are an indispensable tool for working with Python, but some uses of Python require a barebones script. We could just write these script files in a basic text editor and call them from a Python console, as Python scripts really are just that — basic text files. However, many tools exist to help us write scripts more efficiently. To examine those tools, we’ll first run through a few demos…

» Task 1.1: Write some Python code in a simple text file

Create a new text file, add the following it, and save it.

That’s Python alright, but right now the computer doesn’t recognize it as such

» Task 1.2: Convert your text file to a Python script & open in NotePad++

Change the file’s extension from .txt to .py . (Note that on Windows machines, you’ll need to ensure file extensions are shown.)

Open the .py file in NotePad++

→ Note that NotePad++ recognizes the file as a script and adds formatting: some text appears in color and you can fold lines…

» Task 1.3: Open the Python script in IDLE

Right-click the Python script file file and open it in IDLE (ArcGIS Pro)

This application also shows Python as formatted text

Select Run Module (F5) from the Run menu.

This application can also execute the commands typed in our Python file!

At the >>> prompt in the Python 3.6.9 Shell window that appears, type: print(colors[0] )

This application also allows us to run Python commands typed interactively!

This last application, IDLE, is an integrated development environment or IDE (and there’s a funny reason behind its name). These apps are designed to help us write, run, and debug Python scripts. IDLE is installed along side ArcGIS Pro. However, I have yet to meet a person who actually writes scripts using IDLE. There are so many better IDEs out there. The one we’ll explore next, Spyder, is one of the more popular ones – especially if you are familiar with working with R-Studio…

2. Installing the Spyder IDE

Before we can use the Spyder IDE, we have to install it. (The copy of Python installed with ArcGIS Pro includes Jupyter Notebook, but not Spyder.) To install it, we’ll be getting a preview of Conda environments, which we’ll discuss in more detail later. For now, just follow these directions to install Spyder on your machine…

THE FOLLOWING HAS BEEN REVISED SINCE 24 SEPTEMBER

Spyder v 5.1.5 has a significant flaw in its debugging tools. We need to use a slightly different method to install a more recent version of Spyder that works with ArcPy, and this can only be done via the Python command prompt.

» Task 2.1: Install Spyder v5.3.3 via the Python command prompt

Open the Python Command Prompt, found in the Windows Start Menu, within the ArcGIS sub-menu.

Type and run the following command to clone the default ArcGIS Pro Python environment.

Next, type the following command to activate this environment (this is specific to ArcGIS Pro installs of Python):

Now, install Spyder with the following command:

Spyder is now installed on the machine you are currently logged into, within your personal directory. It will stay there, only accessible to you, until someone removes your account profile. Of course, if you move to a machine you’ve not logged into before (or someone has wiped your profile), you’ll need to repeat these steps to re-install Spyder.

3. Starting Spyder

Starting the Spyder IDE, like starting Jupyter Notebooks, is not as simple as most applications on your machine. Here we’ll examine a few more steps on getting the application started via command line, but then also more easily by a shortcut we can create.

» Task 3.1 — Starting Spyder via Python Command Prompt:

Open a Python Command Prompt (or use the one that’s open).

Ensure that the active Python environment is env859-py3 : it will be shown in the command prompt, preceding the path.

  • If it is not the active environment, set it to be the active environment using the proswap env859-py3 command.

Next, you can start Spyder just by typing the command:

If all goes well, Spyder will open up with your Windows user folder set to the default workspace — this will appear in the upper right corner of the Spyder window.

NOTE: Working directories & Spyder projects

Your Python scripts may read and write files, so it’s good to keep track of where you are in your file system. The location where Spyder will look is your Spyder session’s working directory. By default this is set to your Windows user directory. You can change your working directory in Spyder itself by clicking the icon in the upper right and navigating to a different location. Alternatively, you can set the working directory when you open Spyder using the -w option.

To start Spyder with a specific folder set as the default workspace (here we’ll use “V:\SpyderFolder” (which you’d need to create prior to running this command):

Feel free to give it a try!

Like ArcGIS Pro (and RStudio) Spyder supports project workspaces, meaning folders that will contain your code, your data, and settings to keep track of where everything is. So, even better than starting Spyder in a specific directory is starting Spyder in a specific project directory. This can be done by using -p instead of -w . If you use the -p option, Spyder will create the folder if it doesn’t exist.

Try that, and then look inside the folder. You’ll see a subfolder called .spyproject that holds the preferences and settings for your Spyder coding project.

» Task 3.2 — Creating a shortcut (a Windows batch file ) to start Spyder:

Now, we’ll ease the process by creating a windows shortcut that will open Spyder, setting the default workspace to the folder in which the shortcut is placed. This is a bit trickier than the Jupyter shortcut we created because it has to activate the Python workspace we created when we installed Spyder, i.e., the env859-py3 workspace.

Create a new text file in your SpyderFolder folder, and rename this file to “ OpenSpyder.bat ”.

Open this OpenSpyder.bat file in a text editor (e.g. Notepad++).

Paste the text below into this file:

Close the text editor.

Run the batch file by double-clicking it.

A black command window should appear and eventually the Spyder app will also appear. If you’re curious, this batch file ensure the Python environment in which we installed Spyder is the active Python environment. Then it runs the Spyder.exe command from the correct environment which opens Spyder. And finally, it deactivates the Python environment once you’ve ended your Spyder session.

If ever you want to wipe all your Spyder global settings, type: spyder —reset from your Python command prompt. Alternatively, delete the .spyder-py3 folder from your user directory.

4. Navigating Spyder

Spyder’s default layout

If all goes well, Spyder will have opened and you will see it’s default layout which includes multiple separate panes, each of which may have additional tabs. You can modify the arrangement of these windows, but we’ll stick with the defaults for now. These windows include:

» Task 4.1: Navigate Spyder
  • On the far left is the Project Explorer displays the files in our current workspace.
  • Next from the left is the Editor Pane where you write the sequence of commands that comprise your script.
  • On the right top, you toggle between your Variable Explorer , a File Explorer , Plots, and a Help Window.
    • The Variable Explorer reveals all the variables we’ve assigned in our session and their value.
    • The File Explorer displays the files in our workspace.
    • The Plots window can display graphics output the console window is unable to show.
    • And the Help displays help on a command.
    • The IPython Console is used to type Python commands outside of our script. It works just like a Python code cell in our familiar Jupyter notebook.
    • The History Log stores the last 100 commands you’ve typed into the Console.

    Within the View menu you’ll find options to toggle other panes and views. Spyder is quite a customizable program.

    » Task 4.2: Change the layout to mimic R-Studio

    Many of you have used RStudio and are familiar with its layout. Or perhaps you will someday want to learn R, in which case you’ll likely use RStudio in that effort. Either way, it may be useful to switch Spyder’s layout to one that mimics R-Studio so that work translates well between the two platforms. To do this:

    • Select RStudio Layout from the View > Windows Layouts menu.

    It’s not exactly like RStudio, but it may help. You are, of course, welcome to chose any layout you wish, but you should understand what each pane does. We’ll run through some exercises to dig deeper into what each does.

    5. Using Spyder’s Console

    » Task 5.1: Entering code in Spyder’s console

    Entering Data

    • Type “ x=5 ” in the Console – this is the command to create a variable named x and give it the value 5.
    • If you raise the “Variable explorer” tab you will see that x has been added to the list of variables in Python’s memory.
    • You can also type “ print (x) ” or even just “ x ” in the Console to see the value of x.
    • Now type “ y=4 ” and then “ x+y ”. Notice that this last command does not create a variable, although it does produce an output from the calculation.

    Arrow Keys

    If you use the arrow keys in the Console, you can bring back a previous command so that you can edit and re-execute it.

    Go back to the command “ x+y ” and change it to “ junk=x+y ”. You’ve now created the variable junk.

    What can you type to see its value in the Console?

    6. Using Spyder’s Editor

    » Task 6.1: Creating and running a script

    Create a new script file: File > New File . This will add a new file untitled1.py next to the default temp.py .

    • Note where each of these is configured to be saved…
    • Close the temp.py file.

    Add these commands to your script file:

    Run the entire script by clicking the green arrow — or — hitting F5 — or — Selecting Run > Run .

    → This prompts you to save your script. Spyder will always save your script before running.

    • Save your script into your project folder as script1.py and run the script.
    • Check that the variables are added to your session in the Variable Explorer.
    • Where is the result (“Dog”) displayed?
    » Task 6.2: Debugging a script

    Create a new script file in your Spyder session.

    Add the following code to this script and then save it as script2.py :

    Note that Spyder reveals possible errors in your code. You should see a red next to line 1. Hover your mouse over it and it will reveal what the complaint is, at least in general terms.

    What is the error? Can you fix it?

    Another error appears on line 5. Note that the word “ class ” is blue. *This indicates that the word is a reserved word that cannot be used as a variable name.*

    Rename all instances of “class” to “class_name”.

    Spyder can’t find any more errors! Try running the script…

    You’ll get another error showing up in your console. In this case, the error message states where the error occurs. Some error messages are not as kind and don’t reveal exactly where the error occurs. For this we need debugging tools.

    At what line does the error occur?

    Fix the error by coercing the age variable to be a string, not an integer.

    Run the model again.

    Recap

    Integrated Development Environments, or IDEs, help us write scripts. Fundamentally, they are text editors linked to a Python kernel that can execute our Python scripts, but they also provide code formatting, code completion, a Python shell, debugging tools, and many other features that enable us to interactively write and debug our code.

    What is Python Spyder IDE and How to use it?

    It is always necessary to have interactive environments to create software applications and this fact becomes very important when you work in the fields of Data Science, engineering, and scientific research. The Python Spyder IDE has been created for the same purpose. In this article, you will be learning how to install and make use of Spyder or the Scientific Python and Development IDE.

    Before moving on, let’s take a look at all the topics that are discussed over here:

    • What is Python Spyder IDE?
    • Features of Spyder
    • Python Spyder IDE Installation
    • Creating a file/ Starting a Project
    • Writing the Code
    • Variable Explorer
    • File Explorer
    • Configuring Spyder
    • Help

    What is Python Spyder IDE?

    Spyder is an open-source cross-platform IDE. The Python Spyder IDE is written completely in Python. It is designed by scientists and is exclusively for scientists, data analysts, and engineers. It is also known as the Scientific Python Development IDE and has a huge set of remarkable features which are discussed below.

    Features of Spyder

    Some of the remarkable features of Spyder are:

    • Customizable Syntax Highlighting
    • Availability of breakpoints (debugging and conditional breakpoints)
    • Interactive execution which allows you to run line, file, cell, etc.
    • Run configurations for working directory selections, command-line options, current/ dedicated/ external console, etc
    • Can clear variables automatically ( or enter debugging )
    • Navigation through cells, functions, blocks, etc can be achieved through the Outline Explorer
    • It provides real-time code introspection (The ability to examine what functions, keywords, and classes are, what they are doing and what information they contain)
    • Automatic colon insertion after if, while, etc
    • Supports all the IPython magic commands
    • Inline display for graphics produced using Matplotlib
    • Also provides features such as help, file explorer, find files, etc

    Python Spyder IDE Installation ( Installing with Anaconda — Recommended)

    The Python Spyder IDE comes as a default implementation along with Anaconda Python distribution. This is not just the recommended method but also the easiest one. Follow the steps given below to install the Python Spyder IDE:

    Name already in use

    spyder / spyder / plugins / help / utils / tutorial.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

    Spyder: The Scientific Python Development Environment

    Spyder is an Integrated Development Environment (IDE) for scientific computing, written in and for the Python programming language. It comes with an :guilabel:`Editor` to write code, a :guilabel:`Console` to evaluate it and view the results at any time, a :guilabel:`Variable Explorer` to examine the variables defined during evaluation, and several other facilities to help you effectively develop the programs you need as a scientist.

    This tutorial was originally authored by Hans Fangohr from the University of Southampton (UK), and subsequently updated for Spyder 3.3.x by the development team (see Historical note for more details).

    First steps with Spyder

    This section is aimed at Python and Spyder beginners. If you find it too simple, please continue to the next one.

    Execute a given program

    We are going to run this program as a first example:

    Please create a new file in the Spyder :guilabel:`Editor` pane (with :menuselection:`File —> New file` , or Ctrl-N / Command-N ). Then copy and paste the code inside the box above into the file, and save it with the name :file:`hello.py` .

    To execute the program, select :menuselection:`Run —> Run` from the menu (or press F5 ), and confirm the Run settings if required.

    If this is your first time running something, you should see an output like this:

    If so, then you have just run your first Python program — well done.

    The particular paths shown inside runfile() will depend on where you have saved the file, but this is inserted by Spyder automatically.

    What happens when you execute a program?

    Python reads the file line by line, ignoring comments (i.e. lines starting with the # symbol).

    When it comes across the def keyword, it knows that a function is DEFined in this and the next (one or more) lines. All indented lines following def hello(): belong to the function body.

    Note that the function object is created at this point in the file, but the function is not yet called (i.e. not executed).

    When the Python interpreter encounters commands (other than def . and a few other keywords) that are written in the left-most column, it will execute these immediately.

    In the :file:`hello.py` file this is only the line reading hello() which will actually call (i.e. execute) the function with name hello .

    If you comment or remove the line hello() from the program and run the whole file again (by pressing F5 , or selecting :menuselection:`Run —> Run` ), nothing will be printed (because the function hello is defined but not called, i.e. not executed).

    Now you should know how to execute a Python program that you have in the :guilabel:`Editor` pane in Spyder using the :guilabel:`IPython Console` .

    If you are just starting to learn Python, this is probably a good point to return to your text book/course and look at further basic examples.

    The next section gives more detailed information how you can execute parts of your code from the :guilabel:`Editor` in the :guilabel:`IPython Console` . This is a more advanced technique but can be very useful. You may also be interested in the option to execute «cells», chunks of code that are separated by delimiters.

    Call existing functions in the Console

    Once you have executed the :file:`hello.py` program, the function object hello is defined and known to the :guilabel:`IPython Console` . We can thus call the function from the :guilabel:`Console` .

    Type hello() in the :guilabel:`Console` (next to In [?] prompt, where ? is a count of the number of times you’ve executed something), and press the Enter key.

    You should find that the hello() function is executed again, i.e. printing Hello World a second time. Your function call at the :guilabel:`Console` together with the output should look like this:

    Can you see how this differs from executing the whole program again?

    When we execute the whole program (by pressing F5 ), Python goes through the file, creates the hello function object (overriding the previous object), reaches the hello() line and calls the function.

    When we call hello() in the :guilabel:`Console` , we only call the function object hello that has been defined in the :guilabel:`IPython Console` when we executed the whole :file:`hello.py` file earlier (by pressing F5 ).

    This will become clearer over time, as we work with larger examples. You may want to return to this tutorial at a slightly later stage.

    Inspecting objects defined in the Console

    Python provides a function that displays all known objects in the current namespace of the :guilabel:`Console` , called dir . Type dir() at the prompt, and ignore everything starting with an underscore ( _ ) for now. Can you see hello in the list?

    If you get a long list of defined objects, then Spyder may have done some convenience imports for you already. To address this you may want to reset the namespace, execute :file:`hello.py` again by pressing F5 , then run dir() as suggested above.

    Once an object is visible in the current namespace (as is hello in this example), we can use the help function as follows to learn about it. Typing help(hello) at the :guilabel:`Console` prompt, you should see an output like this:

    Where does Python get that information from? Some of it (like the number of input arguments and names of those variables; here we have none) Python can find through inspecting its objects. Additional information comes from the documentation string provided for the function object hello . The documentation string, or docstring, is the first string immediately below the line def hello(): . By convention, and as they usually extend over multiple lines, they are enclosed by triple double quotes ( «»» ).

    The Spyder environment also provides a :guilabel:`Help` pane which by default is located in the top right corner.

    While the cursor is on the name of an object, press Ctrl-I (or Command-I on macOS), and you should find that the same information as we obtained from help(hello) is provided automatically in the :guilabel:`Help` pane:

    images/spyder-hello-docstring.png

    Let’s say you wanted to change how an existing function behaves — how should you get Python to recognize your changes?

    Simple strategy: Re-execute whole program

    In the :guilabel:`Editor` window, change the function hello so that it prints Good Bye World rather than Hello World .

    Press F5 (to execute the whole program)

    Check that the output of the program is now:

    What has happened when you pressed F5 is this: Python has gone through the :file:`hello.py` file and created a new function object hello (overriding the function object hello we had defined before) and then executed the function.

    Looking at the details

    We’ll now investigate this behavior in a little more depth:

    We need to start with a clearly defined state. To do this, please change the function hello() back so that it prints Hello World , then press F5 to run the whole program and check that it prints Hello World .

    Call the function hello() from the command prompt (as described previously). You should see Hello World printed.

    Now change the function definition so that it would print Later World , and save the file (but do NOT execute the program, i.e. do NOT press F5 yet).

    Call the function hello() in the :guilabel:`Console` again. You should find that the text printed reads Hello World , like here:

    Why is this so? Because the hello function object in the :guilabel:`Console` is the old one which prints Hello World . So far, we have changed the file :file:`hello.py` (and replaced Hello World in there with Later World ) in the :guilabel:`Editor` but this has not affected the objects that have previously been created in the :guilabel:`Console` .

    To update the console’s namespace with modified function, we have two options:

    Option 1: Execute the whole file :file:`hello.py` again by pressing F5 : this creates a new function object hello (and overrides the old one). You should find that if you press F5 , and then call hello() at the prompt, the new text Later World is printed.

    Option 2: Select the region you have changed (in this case the whole function hello , starting from the line def hello(): down to print(«Later World») , then click :menuselection:`Run —> Run selection or current line` or press F9 .

    This will update the hello object in the :guilabel:`Console` without having to execute the whole :file:`hello.py` file:

    If we now type hello() , we see the updated response:

    The ability to execute parts of the code to update some objects in the :guilabel:`Console` (in the example above, we updated the function object hello ), is of great use when developing and debugging more complex programs, and when re-creating objects/data in the :guilabel:`Console` session takes time. For example, by modifying only the functions (or classes/objects, etc). that we are actually developing or debugging, we can keep re-using the data and other objects created previously.

    Recommended first steps for Python beginners

    Before we begin, make sure to have an :guilabel:`IPython Console` open (bottom-right by default). This uses the IPython interpreter, standard in the scientific community. To open a new :guilabel:`Console` at any time, select :menuselection:`Consoles —> Open an IPython Console` .

    Reset the namespace

    The namespace (i.e. the collection of objects defined in the :guilabel:`Console` at any given time) can be cleared in IPython using the %reset command. Type %reset and press Enter , then confirm with y :

    You can also accomplish the same thing by selecting Remove all variables from the «Gear» option menu in the top right of the :guilabel:`IPython Console` pane. We discuss this a little further, but you can skip the following if you are not interested.

    After issuing the %reset command or selecting Remove all variables , we should only have a few objects defined in the namespace of that session. We can list all of them using the dir() command:

    Finally, if you like to skip the confirmation step of the reset command, you can use %reset -f instead of %reset ; or, tick the Don’t show again checkbox in the Remove all variables dialog.

    Strive for PEP8 Compliance

    In addition to the syntax that is enforced by the Python programming language, there are additional conventions regarding the layout of the source code, in particular the Style Guide for Python source code known as «PEP 8». By following this guide and writing code in the same style as almost all Python programmers do, it becomes easier to read, and thus easier to debug and re-use — both for the original author and others.

    To have Spyder check this for you automatically, see the next section.

    Where are the preferences?

    A lot of Spyder’s behaviour can be configured through its Preferences. Where this is located in the menu depends on your operating system:

    • On Windows and Linux, go to :menuselection:`Tools —> Preferences`
    • On macOS, navigate to :menuselection:`Python/Spyder —> Preferences`

    Warn if PEP 8 code style guidelines are violated

    Automatic Symbolic Python

    Through :menuselection:`Preferences —> IPython console —> Advanced Settings —> Use symbolic math` we can activate the console’s SYMbolic PYthon (sympy) mode that is provided by the SymPy Python package. This allows nicely rendered mathematical output (LaTeX style), imports some SymPy objects automatically when the :guilabel:`IPython Console` starts, and reports what it has done. You’ll need to have SymPy installed for it to work, and a LaTeX distribution on your system to see the formatted output (see the Getting LaTeX page on the LaTeX site to acquire the latter, if you don’t already have it).

    We can now use the variables x and y , for example like this:

    images/spyder-sympy-example.png

    Shortcuts for useful functions

    The following are the default shortcuts; however, those marked with * can be customized through the Keyboard shortcuts tab in the Preferences. Also, macOS users should substitute Command for Ctrl , and Option for Alt .

    F5 * executes the current file.

    F9 * executes the currently highlighted chunk of code; this is very useful to (say) update definitions of functions in the :guilabel:`Console` session without having to run the whole file again. If nothing is selected, F9 * executes the current line.

    Tab * auto-completes commands, function names, variable names, and methods in the :guilabel:`Console` and the :guilabel:`Editor` . This feature is very useful, and should be employed routinely. Do try it now if auto-completion is new to you. Assume you have defined a variable:

    Suppose we need to write code that computes mylongvariablename + 100 . We can simply type my and then press the Tab key. The full variable name will be completed and inserted at the cursor position if the name is unique, and then we can carry on and type « + 100«. If the name is not uniquely identifiable given the letters my , a list field will be displayed from which the desired variable can be chosen. Choosing from the list can be done with the Up and Down keys with the Enter key to select, or by typing more letters of the name in question (the selection will update automatically) and confirming by pressing Enter when the appropriate name is identified.

    Ctrl-Enter * executes the current cell (menu entry :menuselection:`Run —> Run cell` ). A cell is defined as the code between two lines which start with the characters #%% , # %% or # <codecell> .

    Shift-Enter * executes the current cell and advances the cursor to the next cell (menu entry :menuselection:`Run —> Run cell and advance` ).

    Cells are useful for breaking large files or long blocks of code into more manageable chunks. Like those in an IPython notebook, each cell can be run independently.

    Alt-Up * moves the current line up. If multiple lines are highlighted, they are moved up together. Alt-Down * works correspondingly, moving line(s) down.

    Ctrl-LeftMouseButton or Alt-G * on a function/method in the :guilabel:`Editor` opens a new :guilabel:`Editor` tab showing the definition of that function.

    Shift-Ctrl-Alt-M * maximizes the current window (or changes the size back to normal if pressed in a maximized window).

    Ctrl-Shift-F * activates the Find in Files pane, allowing grep -like searches across all files in a specified scope.

    Ctrl — = will increase the font size in the :guilabel:`Editor` or the :guilabel:`Console` , whereas Ctrl — — will decrease it.

    The font face and size for other parts of the UI can be set under :menuselection:`Preferences —> General —> Appearance —> Fonts` .

    Ctrl-S * in the :guilabel:`Editor` saves the file currently being edited. This also forces various warning triangles in the left column of the :guilabel:`Editor` to be updated (otherwise they update every 2.5 seconds by default, which is also configurable).

    Ctrl-S * in the :guilabel:`Console` saves the current IPython session as an HTML file, including any figures that may be displayed inline. This is useful as a quick way of recording what has been done in a session.

    (It is not currently possible to load this saved record back into the session — if you need functionality like this, look for the IPython Notebook).

    Ctrl-I * when pressed while the cursor is on an object opens documentation for that object in the help pane.

    These are the settings that define how the file in the :guilabel:`Editor` is executed if we select :menuselection:`Run —> Run` or press F5 .

    By default, the settings box will appear the first time we try to run a file. If we want to change the settings at any other time, they can be found under :menuselection:`Run —> Configure` or by pressing F6 .

    There are three choices for the :guilabel:`Console` to use, of which I’ll discuss the first two. Let’s assume we have a program :file:`hello.py` in the :guilabel:`Editor` which reads

    Execute in current console

    This is the default option, and generally a good choice.

    Persistence of objects after code execution

    Choosing the Execute in current console setting under :menuselection:`Run —> Configure` means that:

    • When the execution of :file:`hello.py` is completed, we can interact with the :guilabel:`Console` in which the program ran.
    • In particular, we can inspect and interact with objects that the execution of our program created, such as i and hello() .

    This is generally very useful for incremental coding, testing and debugging. For example, we can call hello() directly from the :guilabel:`Console` prompt, and don’t need to execute the whole :file:`hello.py` for this (although if we change the function hello() , we need to execute the file, or at least the function definition, to make the new version of hello() visible at the :guilabel:`Console` ; either by re-executing the whole script or via :menuselection:`Run —> Run Selection` ).

    Persistence of objects from before code execution

    However, executing the code in the :guilabel:`Editor` in the current :guilabel:`Console` also entails a third effect:

    • The code that executes can see other (global) objects that were defined in the :guilabel:`Console` session.

    This persistence of objects is easily forgotten and usually not required when working on small programs (although it can be of great value occasionally). These objects could come from previous execution of code, from interactive work in the :guilabel:`Console` , or from convenience imports such as from sympy import * (Spyder may do some of those convenience imports automatically).

    This visibility of objects in the :guilabel:`Console` namespace to the code we execute may also result in coding mistakes if the code inadvertently relies on these objects.

    Here is an example: Imagine that:

    1. We run the code :file:`hello.py` . Subsequently, the variable i is known in the :guilabel:`Console` as a global variable.
    2. We edit the :file:`hello.py` source and accidentally delete the line i = 42 .
    3. We execute the file containing :file:`hello.py` again. At this point, the call of hello(i) will not fail because the :guilabel:`Console` has an object of name i defined, although this is not defined in the source of :file:`hello.py` .

    At this point, we could save :file:`hello.py` and (falsely) think it would execute correctly. However, running it in a new :guilabel:`IPython Console` session (or via python hello.py in a system shell, say) would result in an error, because i is not defined.

    The problem arises because the code makes use of an object (here i ) without creating it first. This also affects importing of modules: if we had imported sympy at the IPython prompt, then our program will see that when executed in this :guilabel:`IPython Console` session.

    To learn how we can double check that our code does not depend on such existing objects, see below .

    Execute in a dedicated console

    Choosing Execute in a dedicated console under :menuselection:`Run —> Configure` will start a new :guilabel:`IPython Console` every time the :file:`hello.py` program is executed. The major advantage of this mode over Execute in current console is that we can be certain that there are no global objects defined in this :guilabel:`Console` which originate from debugging and repeated execution of our code. Every time we run the code in the :guilabel:`Editor` , the :guilabel:`IPython Console` in which the code runs is restarted.

    This is a safe option, but provides less flexibility in interactive execution.

    How to double check your code executes correctly «on its own»

    Assuming you have selected the Execute in current console option, you have two methods to check that your code works on its own (i.e. it does not depend on undefined variables, unimported modules and commands etc):

    Alternatively, if you want to stay with the current :guilabel:`Console` , you can

    First reset the namespace with IPython’s magic %reset command or the Remove all variables menu option, which will clear all objects, such as i in the example above from the current namespace. Then, execute the code from the :guilabel:`Editor` .

    My recommendation for beginners would be to Execute in current console.

    Once you have completed a piece of code, double check that it executes independently using one of the options explained above.

    When multiple files are opened in the :guilabel:`Editor` , the corresponding tabs at the top of the window area are arranged in the order they are opened, but can be easily moved around if you wish.

    On the left of the tabs, there is as icon that shows Browse tabs if the mouse hovers over it. It is useful to jump to a particular file directly, if many files are open. You can also summon the file switcher through tapping Ctrl-Tab or Ctrl-P , which navigates your tabs in most-recently-used order.

    Environment variables can be displayed from the IPython Console window (bottom right window in default layout). Click on the Options menu («Gear» icon), then select Show environment variables .

    Reset all customization

    All customization saved on disk can be reset by calling Spyder from the command line with the switch —reset , i.e. running spyder —reset .

    Objects in the Variable Explorer

    Right-clicking on objects in the :guilabel:`Variable Explorer` displays options to plot and analyze these further.

    Double-clicking on simple variables allows them to be edited directly, and double-clicking on objects opens a new window that displays their contents and often allows them to be edited.

    Python collections (lists, dictionaries, tuples. ), Numpy arrays, Pandas Index , Series and DataFrame , Pillow images and more can each be displayed and edited in specialized GUI viewers, and most arbitrary Python objects can be viewed, browsed and edited like their dict() representation.

    Documentation string formatting

    If you want to document the code you are developing (and you certainly should!), we recommend you write documentation strings (or docstrings) for it, using a special format called reStructuredText (reST). In the scientific Python world, a further set of conventions called the Numpydoc standard is typically followed (although other systems exist). If you follow those guidelines, you can obtain beautifully formatted docstrings in Spyder.

    For example, to get an average() function look like this in the Spyder :guilabel:`Help` pane:

    images/spyder-nice-docstring-rendering.png

    you need to format the documentation string as follows:

    What matters here is that the word Parameters is used, and underlined. The line a : numeric shows us that the type of the parameter a is numeric . In the next line, which is indented, we can write a more extended explanation of what this variable represents, what conditions the allowed types have to fulfill, etc.

    The same for all parameters, and also for the returned value.

    Often it is a good idea to include an example too, as shown.

    Line by line step execution of code

    Start debug execution (with the :menuselection:`Debug —> Debug` menu option or Ctrl-F5 ) to activate the IPython debugger, ipdb . The :guilabel:`Editor` pane will then highlight the line that is about to be executed, and the :guilabel:`Variable Explorer` will display variables in the current context of the point of program execution.

    After entering debug mode, you can execute the code line by line using the Step button of the :guilabel:`Debug` toolbar:

    images/debug-step-over.png

    or the shortcut Ctrl-F10 . You can also inspect how a particular function is working by stepping into it with the Step Into button

    images/debug-step-in.png

    or the shortcut Ctrl-F11 . Finally, to get out of a function and continue with the next line you need to use the Step Return button

    images/debug-step-out.png

    or the shortcut Ctrl-Shift-F12 .

    If you prefer to inspect your program at a specific point, you need to insert a breakpoint by pressing F12 on the line on which you want to stop, or clicking to the right of the line number. A red dot in this position indicates a breakpoint; it can be removed by repeating the same procedure.

    After entering the Debugger, you can press the Continue button

    images/debug-continue.png

    to stop the execution at the first breakpoint.

    You can also control the debugging process by issuing these commands at the :guilabel:`Console` prompt:

    • n to move to the Next statement.
    • s to Step into the current statement. If this is a function call, step into that function.
    • r to complete all statements in the current function and return from that function before returning control.

    Inside the debugger, you can also interactively execute many of the statements you can normally, including assigning and modifying variables, defining and calling functions, setting new breakpoints, and more.

    For example, enter the following code into a new or temporary file:

    If we execute this ( :menuselection:`Run —> Run` ), we should see the output:

    Now run this using the debugger ( :menuselection:`Debug —> Debug` ), press the Step button until the highlighted line reaches the demo(0) function call, then press the Step into to inspect this function. Keep pressing the Step button to execute the next lines. Then, modify x by typing x = 10 in the debugger prompt. You should see x changing in the :guilabel:`Variable Explorer` and when its value is printed as part of the demo() function. (The printed output appears between your debugger commands and responses).

    This debugging ability to execute code line by line, to inspect variables as they change, and to modify them manually is a powerful tool to understand what a piece of code is doing (and to correct it if desired).

    To terminate the debugger, you can type exit , select :menuselection:`Debug —> Stop` or press Ctrl-Shift-F12 .

    Debugging once an exception has occurred in the Console

    In the :guilabel:`IPython Console` , we can call %debug straight after an exception has been raised: this will start the IPython debug mode, which allows inspection of local variables at the point where the exception occurred as described above. This is a lot more efficient than adding print statements to the code an running it again.

    If you use this, you may also want to use the commands up (i.e. press u at the debugger) and down (i.e. press d ) which navigate the inspection point up and down the stack. (Up the stack means to the functions that have called the current function; down is the opposite direction). You can also enable (or disable) this debugger being triggered automatically when an exception occurs by typing pdb at any time.

    You can decide whether figures created with Matplotlib will show

    • Inline, i.e. inside the :guilabel:`IPython Console` , or
    • Inside a new window, with an options toolbar.

    The first option is convenient to save a record of the interactive session ( Ctrl-S in the console).

    The second option allows you to interactively zoom into the figure, manipulate it, set various plot and display options, and save it to different file formats via a menu.

    The command to get the figures to appear inline in the :guilabel:`IPython Console` is:

    The command to get figures appear in their own window (rendered by the Qt backend) is:

    Here are two lines you can use to quickly create a plot and test this:

    This tutorial was originally based on notes by Hans Fangohr, that are used at the University of Southampton to teach Python for computational modelling to undergraduate engineers and postgraduate PhD students for the Next Generation Computational Modelling doctoral training centre.

    Getting started with Anaconda¶

    Anaconda Distribution contains conda and Anaconda Navigator, as well as Python and hundreds of scientific packages . When you installed Anaconda, you installed all these too.

    Conda works on your command line interface such as Anaconda Prompt on Windows and terminal on macOS and Linux.

    Navigator is a desktop graphical user interface that allows you to launch applications and easily manage conda packages, environments, and channels without using command-line commands.

    You can try both conda and Navigator to see which is right for you to manage your packages and environments. You can even switch between them, and the work you do with one can be viewed in the other.

    Try this simple programming exercise, with Navigator and the command line , to help you decide which approach is right for you.

    When you’re done, see What’s next? .

    Your first Python program: Hello, Anaconda!¶

    Use Anaconda Navigator to launch an application. Then, create and run a simple Python program with Spyder and Jupyter Notebook. Watch our short training videos on Anaconda Learning to get up and running with Jupyter Notebook and JupyterLab, along with several other popular integrated development environments (IDEs):

    ../../../_images/learning-ad2.png

    Open Navigator¶

    Choose the instructions for your operating system.

    Windows

    From the Start menu, click the Anaconda Navigator desktop app.

    macOS

    Open Launchpad, then click the Anaconda Navigator icon.

    Linux

    Open a terminal window and type anaconda-navigator .

    Navigator’s Home page displays several applications for you to choose from. For more information, see links at the bottom of this page.

    Run Python in Spyder IDE (integrated development environment)¶

    More of a visual learner? Follow along with Create a simple Python program in Spyder on Anaconda Learning instead!

    On Navigator’s Home tab, in the Applications pane on the right, scroll to the Spyder tile and click the Install button to install Spyder.

    If you already have Spyder installed, you can jump right to the Launch step.

    Launch Spyder by clicking Spyder’s Launch button.

    In the new file on the left, delete any placeholder text, then type or copy/paste print("Hello Anaconda") .

    In the top menu, click File — Save As and name your new program hello.py .

    Run your new program by clicking the triangle Run button.

    You can see your program’s output in the bottom right Console pane.

    ../../../_images/getting-started_Spyder.png

    Close Spyder¶

    From Spyder’s top menu bar, select Spyder — Quit Spyder (In macOS, select Python — Quit Spyder).

    Run Python in a Jupyter Notebook¶

    More of a visual learner? Watch our short training videos on Jupyter Notebook and JupyterLab on Anaconda Learning instead!

    On Navigator’s Home tab, in the Applications pane on the right, scroll to the Jupyter Notebook tile and click the Install button to install Jupyter Notebook.

    If you already have Jupyter Notebook installed, you can jump right to the Launch step.

    Launch Jupyter Notebook by clicking Jupyter Notebook’s Launch button.

    This will launch a new browser window (or a new tab) showing the Notebook Dashboard.

    ../../../_images/jupyter-dashboard.png

    On the top of the right hand side, there is a dropdown menu labeled “New”. Create a new Notebook with the Python version you installed.

    Rename your Notebook. Either click on the current name and edit it or find rename under File in the top menu bar. You can name it to whatever you’d like, but for this example we’ll use MyFirstAnacondaNotebook.

    In the first line of the Notebook, type or copy/paste print("Hello Anaconda") .

    Save your Notebook by either clicking the save and checkpoint icon or select File — Save and Checkpoint in the top menu.

    Run your new program by clicking the Run button or selecting Cell — Run All from the top menu.

    ../../../_images/getting-started_Jupyter.png

    Close Jupyter Notebook¶

    1. From Jupyter Notebooks top menu bar, select File — Close and Halt.
    2. Click the Quit button at the upper right of the Notebook Dashboard and close the window or tab.

    Close Navigator¶

    From Navigator’s top menu bar, select Anaconda Navigator — Quit Anaconda-Navigator.

    Write a Python program using Anaconda Prompt or terminal¶

    Open Anaconda Prompt¶

    Choose the instructions for your operating system.

    Windows

    From the Start menu, search for and open “Anaconda Prompt”:

    macOS

    Open Launchpad, then click the terminal icon.

    Linux

    Open a terminal window.

    Start Python¶

    At Anaconda Prompt (terminal on Linux or macOS), type python and press Enter.

    The >>> means you are in Python.

    Write a Python program¶

    At the >>> , type print("Hello Anaconda!") and press Enter.

    When you press enter, your program runs. The words “Hello Anaconda!” print to the screen. You’re programming in Python!

    Exit Python¶

    On Windows, press CTRL-Z and press Enter. On macOS or Linux type exit() and press Enter.

    Optional: Launch Spyder or Jupyter Notebook from the command line¶

    1. At the Anaconda Prompt (terminal on Linux or macOS), type spyder and press Enter. Spyder should start up just like it did when you launched it from Anaconda Navigator.
    2. Close Spyder the same way you did in the previous exercise.
    3. At the Anaconda Prompt (terminal on Linux or macOS), type jupyter-notebook and press Enter.

    Jupyter Notebook should start up just like it did when you launched it from Anaconda Navigator. Close it the same way you did in the previous exercise.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *