Skip to content

Latest commit

 

History

History
1436 lines (842 loc) · 41.4 KB

File metadata and controls

1436 lines (842 loc) · 41.4 KB

Spyder IDE Ubuntu Setup

Linux Terminal

The Linux Terminal can be opened from the Start Menu or using the shortcut Ctrl, Alt + t:

img_001

The Linux Terminal uses the bash programming language by default. The bash prompt begins with:

user@pcname

img_002

Followed by the current working directory:

~

Followed by a:

$

img_003

Where ~ means the Home directory:

img_004

If Other Locations are selected:

img_005

there is a usr folder:

img_006

Which contains a binary bin folder:

img_007

This contains the binaries that can be ran from the Terminal. On Ubuntu, which is Debian based there is the package manager apt:

img_008

When:

apt

is input, this binary is executed:

img_009

the binary clear may be used to clear the Terminal:

clear

img_010

img_011

There is also a bin folder on the root of the drive, which is the binaries used by the system:

img_012

To install packages, system wide using apt, the prefix sudo is used, which stands for super user do:

sudo apt

img_013

Switching to a super user will prompt for authentication. Input your account password in order to proceed:

img_014

img_015

img_016

Details about commands available to use with the apt binary are shown. the install command can be used to install a number of TeX fonts (which will later be used by matplotlib):

sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-plain-generic cm-super dvipng

To copy and paste in the terminal, use the right click or keyboard shortcut keys Ctrl, + c or Ctrl, + v:

img_017

Input y in order to proceed:

img_018

The packages will be downloaded and installed:

img_019

Returning to the usr folder:

img_020

The user bin folder can be examined:

img_021

Notice there is the programming languages bash and python3:

img_022

img_023

If a new Terminal is opened without super user privileges, python3 can be launched using:

python3

Notice the prompt changes as a different programming language is now used:

img_024

if the datetime module is imported, its __file__ attribute can be examined:

>>> import datetime
>>> datetime.__file__
'/usr/lib/python3.12/datetime.py'

img_025

Note the Python standard library is found in the lib subfolder, this can be examined:

img_026

There is a python3.12 subfolder:

img_027

Which contains the standard modules such asdatetime.py:

img_028

Some standard modules have multiple script files and are contained in a folder. This folder has the data model initialisation file __init__ which is imported when the folder is imported:

>>> import email
>>> email.__file__
'/usr/lib/python3.12/email/__init__.py'

img_029

img_030

img_031

Note the absence of the site-packages subfolder:

img_032

This means no third-party libraries are installed. Therefore if numpy is attempted to be imported::

>>> import numpy as np
ModuleNotFoundError: No module named 'numpy'

img_033

The python shell can be exited using the exit function:

exit()

img_034

This returns to the bash shell:

img_035

This can be cleared using:

clear

img_036

If text editor is opened:

img_037

img_038

The file can be saved using File → Save As:

img_039

The file is saved in Documents:

img_040

Using the file name script.py with the .py file extension. This means the text editor, will apply Python syntax highlighting:

img_041

The following Python code can be input:

print('Hello World!')

img_042

The Documents folder can be opened in the Terminal, by right clicking empty space in the folder and selecting Open in Terminal:

img_043

Notice the path is now ~/Documents:

img_044

The path can be changed using the binary cd which stands for change directory. .. means the parent folder:

cd ..

img_045

img_046

. means in the same folder as. In this case Downloads is a subfolder of ~:

cd ./Downloads

img_047

To go back to Documents, the parent folder can be accessed and Documents selected from is:

cd ../Documents

img_048

The ~ means Home:

cd ~

img_049

And Documents can be selected frm Home using:

cd ~/Documents

img_050

The binary ls will list all the files and folders in the current working directory:

ls

img_051

The binary python3 can be run supplying the script file as a command line input argument:

python3 script.py

img_052

The print statement displays:

img_053

If another file is created in the text editor, this time with the extension .sh:

img_054

img_055

img_056

bash is a slightly different scripting language to Python, optimised for navigation around the operating system. If the following is input:

echo "Hello World!"

img_057

The binary ls can be used to view all the files:

ls

img_058

The binary bash can be run supplying the script file as a command line input argument:

bash script.sh

img_059

Downloading and Installing Spyder

Spyder is developed on GitHub and the latest release is on the GitHub Spyder Releases Page. Select the Linux Installer:

img_060

Notice that this is .sh Shell Script:

img_061

img_062

Right click the Downloads folder and select Open in Terminal:

img_063

This script can be ran using bash:

img_064

Input:

bash S↹

And the file name should auto-complete:

img_065

bash Spyder-Linux-x86_64.sh

Press to execute the script:

img_066

Press to begin scrolling through the license agreement:

img_067

Press q to quit scrolling:

img_068

To accept the license agreement input yes and press :

img_069

To install in the default location press :

img_070

Spyder is now installed and a Start Menu shortcut is now created:

img_071

Spyder IDE Basics

When Spyder is first launched, a prompt to begin a tour will display:

img_072

To the bottom right is the IPython Console, where commands can be input individually. Notice the cells are numbered, by execution oder. The code can be input:

In [1]: 'hello'
Out[1]: 'hello'

img_073

This value was input and returned as an output. the value can also be assigned to an object name using the = operator:

In [2]: text = 'hello'

img_074

This object name text displays on the Variable Explorer. It has the type str. The identifiers from the str class can be accessed from text by typing in text. followed by a :

img_075

If part of an identifier is input for example text.cap followed by a , the identifier text.capitalize will display:

img_076

img_077

When this is input, the method is referenced and the output displays where the method is defined, in this case, in the str class:

In [3]: text.capitalize
Out[3]: <function str.capitalize()>

img_078

A method is called using parenthesis, the docstring displays, which provided details about any input parameters:

img_079

A new str instance is returned to the console:

In [4]: text.capitalize()
Out[4]: 'Hello'

img_080

Note text remains assigned to the original str instance 'hello'. This new str instance can be assigned to text which reassigns the value of text. The right hand side is carried out first (using the original value of text which was hello)

In [5]: text.capitalize()

This is then reassigned to the object name on the right hand side

In [5]: text = text.capitalize()

The value of the new instance now displays under text in the Variable Explorer:

img_081

img_082

Other methods such as replace can be examined. A docstring displays showing the mandatory positional parameters old (position 0) and new (position 1). This is followed by the optional parameter value (position 2) which has a default value -1, meaning all replacements of the old substring will be replaced with the new substring. Any parameter provided before the / must be supplied positionally only:

img_083

The identifier can be inspected, by right clicking the identifier and pressing inspect or Ctrl + i:

img_084

This displays documentation in the help pane:

img_085

In [6]: text.replace('ll', '7')
Out[6]: 'He7o'

Using named parameters:

In [7]: text.replace(old='ll', new='7')

is not allowed because these parameters occur before the / in the docstring

img_086

The a new str instance is returned which ahs the specified replacement:

img_087

Spyder has a script editor.

img_088

The script file can be saved in Documents as script.py:

img_089

img_090

img_091

img_092

In a Python script the # means a comment:

# Import Libraries
import numpy as np # numeric python library
import matplotlib.pyplot as plt # matrix plotting library

img_093

Using #%% creates a cell:

#%% Import Libraries
import numpy as np 
import matplotlib.pyplot as plt 

Cells can be collapsed:

img_094

img_095

Identifiers display if a . is used following an object name. If the identifier is a docstring, the docstring will display:

img_096

Other cells can be created:

#%% Import Libraries
import numpy as np 
import matplotlib.pyplot as plt 
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * x
#%% Plot Data
plt.plot(x, y)

img_097

A cell from a script file can be ran using the run cell button:

img_098

This cell is still highlighted after execution. The cell and advance to the next cell button is more useful when running through each cell in a script file:

img_099

img_100

The Variables x and y display in the Variable Explorer:

img_101

The plot displays as a static image using the inline backend. This static images displays on the plots pane:

img_102

The plotting backend can be changed to an interactive plot using the qtagg backend:

img_103

img_104

If the last line is selected, the currently selected selection can be run:

img_105

The plot now displays in its own window:

img_106

The kernel can be restarted, removing all variables and imports by selecting Consoles → Restart Kernel and then selecting Yes. Alternatively typing exit into the console restarts the kernel:

img_107

img_108

All variables and imports are lost and the cell execution number returns to 1:

img_109

the script editor will display a list of identifiers from an object name after a .:

img_110

The figure can be saved using:

#%% Import Libraries
import numpy as np 
import matplotlib.pyplot as plt 
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * x
#%% Plot Data
plt.plot(x, y)
#%% Save Figure
plt.savefig('fig1.png')

img_111

The entire Script file can be run, using Run File:

img_112

the files pane displays the current working directory, which is the same folder, that the script.py file is stored in. Note fig1.png is also saved here:

img_113

It can be opened externally:

img_114

img_115

If a deliberate mistake is made in the code, that would introduce a SyntaxError notice that the script editor displays a warning:

img_116

The following code will run, but is not formatted correctly:

img_117

Spacing issues can be corrected using the autopep8 formatter. Select format file or extension with autopep8:

img_118

Spyder also has the opinionated formatter black, however black's opinionated formatting gives string quotations that are inconsistent to Python and Python standard libraries. Ruff integration with a ruff.toml file which can be used to specify a preferred quote option such as single quotes isn't available but is a planned feature:

img_119

A custom function can be created:

def greet_user(user_name):
    |

Note every line of code belonging to the code block is indented by 4 spaces:

img_120

Blank spaces can be shown on the script editor by selecting source → show blank spaces:

img_121

img_122

The function can be completed:

def greet_user(user_name):
    print(f'Hello {user_name}')

img_123

A docstring template can be autogenerated for the function by inputting:

def greet_user(user_name):
    """
    print(f'Hello {user_name}')

img_124

def greet_user(user_name):
    """
    

    Parameters
    ----------
    user_name : TYPE
        DESCRIPTION.

    Returns
    -------
    None.

    """
    print(f'Hello {user_name}')

img_125

def greet_user(user_name):
    """
    greets the user

    Parameters
    ----------
    user_name : str
        The name of the user.

    Returns
    -------
    None.

    """
    print(f'Hello {user_name}')

img_126

Note code not part of the function is not indented:

def greet_user(user_name):
    """
    greets the user

    Parameters
    ----------
    user_name : str
        The name of the user.

    Returns
    -------
    None.

    """
    print(f'Hello {user_name}')


print('Code not part of the function')

img_127

Another cell can be made to call the function:

img_128

Notice that when the function name is input:

greet_user

that the docstring created displays:

img_129

This function can be called and provided with the input string 'Philip':

greet_user('Philip')

img_130

When this script file is run, the function is called and the print function in the functions body is used to print 'Hello Philip' which is shown in the cell output:

img_131

In the above script file, the function is defined and called. If this script file is saved as another script file called module.py:

img_132

img_133

Both script.py and module.py can be viewed, side by side by selecting split horizontally:

img_134

Both script.py and module.py are found in the same folder:

img_135

In module.py where the function is defined and called, the calling of the function can be commented out. Multiple lines of code can be commented out by highlighting them and selecting Edit → Comment/Uncomment:

img_136

This prevents these lines of code from being executed but doesn't delete them, so they can be uncommented out later on:

img_137

This means that module.py can be imported in script.py using:

import module # no file extension

img_138

Identifiers from the module can be accessed using a .:

import module 
module.

img_139

The function greet_user can be accessed from the imported module:

img_140

If the panel with module.py is closed, code can be input in script.py:

img_141

img_142

If the panel with module.py is closed, code can be input in script.py:

import module 
module.greet_user('Philip')

When run, the print statement displays in the console:

img_143

exit will be input to restart the kernel which prevents some issues such as reloading modules. Essentially when an instruction is made to reload a module, it will be skipped as there is a performance loss by loading the same module twice. This is problematic when working on the module as changes aren't reflected:

img_144

img_145

An instruction can be made to import an identifier from a module, notice that the code completion displays the identifier user_greeting:

from module import u

img_146

from module import user_greeting

img_147

And the function can be called as before:

from module import user_greeting
user_greeting('Philip')

img_148

exit is used to restart the kernel. If the module module.py is copied into a subfolder subfolder. The module can be accessed from the subfolder by use of a . in this case:

from subfolder.module import user_greeting
user_greeting('Philip')

img_149

exit is used to restart the kernel. module.py can be copied and renamed to __init__.py. __init__.py is known as the initialisation file, that is imported when the folder is imported:

from subfolder import user_greeting
user_greeting('Philip')

img_150

Identifiers beginning with a double underscore __ and ending in __ are part of the Python datamodel, colloquially they are sometimes called dunder identifiers. These can be accessed from the str instance text by inputting:

text = 'hello'
text.__

img_151

In the console the data model identifiers can be viewed by inputting:

text.__

followed by a :

img_152

If the __add__ data model identifier for example is selected and input with open parenthesis, the docstring displays:

text.__add__(

Note the return value instructs the preferred builtins function or operator to use, in this case +:

text + text

img_153

img_154

The operator behind the scenes uses:

text.__add__(text)

Where the text instance before the . is the str instance the method is called from known as self. The second instance provided in the function is known as value:

img_155

img_156

This method is defined in the str class. Note when called from the str class, the instance self must be provided, in addition to the instance value:

str.__add__(text, text)

img_157

img_158

There are a number of data model identifiers in the script file which can be accessed using __ In this case the data model identifiers __file__ and __name__ will be examined:

img_159

These can be accessed in the script file:

__file__
__name__

However will not be shown in the console when the script file is run.

img_160

To view these in the console, they can be printed in the script file:

print(__file__)
print(__name__)

img_161

Note when this file is run, i.e. is the first input argument to the ipython magic %runfile, it is regarded as the main script file being executed and has the data model __name__ as '__main__':

img_162

module.py and script.py can be opened side by side. If the following code is in module:

print(__file__)
print(__name__)

And if the following code is in script:

import module

When script.py is run, the code in the module is run as it is imported. Notice that __name__ is now 'module' and not '__main__'. This is because the first input argument %runfile is script.py and this is the main script known as '__main__':

img_163

If module.py is updated to:

text = 'hello'

if __name__ == '__main__':
    print('Diagnostic Code')

When the kernel is restarted and module is run, the instance text is instantiated and is shown on the Variable Explorer. It is the '__main__' module and the diagnostic code prints:

img_164

If the module is imported in script.py:

import module

the condition to the if code block is False because this is not the '__main__' module, so the diagnostic code does not run. The variable module.text is instantiated and can be accessed in the console:

img_165

ModuleNotFoundError

The following standard modules can be imported and the __file__ attribute of the modules can be checked:

In [4]: import datetime
In [5]: datetime.__file__
Out[5]: '/home/philip/.local/spyder-6/envs/spyder-runtime/lib/python3.11/datetime.py'
In [6]: import email
In [7]: email__file__
Out[7]: '/home/philip/.local/spyder-6/envs/spyder-runtime/lib/python3.11/email/__init__.py'

img_166

The following third-party libraries can be imported and the __file__ attribute of the modules can be checked:

In [8]: import numpy as np
In [9]: np.__file__
Out[9]: '/home/philip/.local/spyder-6/envs/spyder-runtime/lib/python3.11/site-packages/numpy/__init__.py'
In [10]: import matplotlib.pyplot as plt
In [11]: plt.__file__
Out[11]: '/home/philip/.local/spyder-6/envs/spyder-runtime/lib/python3.11/site-packages/matplotlib/pyplot.py'

Note that pyplot is a module in the library matplotlib.

img_167

If Help → Dependencies is selected:

img_168

A number of mandatory and optional dependencies are listed, which are include libraries from the scientific stack numpy, pandas and matplotlib:

img_169

Notice seaborn is not listed. If it is attempted to be imported:

import seaborn

There is a ModuleNotFoundError:

img_170

spyder-runtime Environment

If folder options are selected and Show Hidden Files is selected:

img_171

The .local folder contains locally installed programs:

img_172

The Spyder IDE is installed in the spyder-6 subfolder:

img_173

Notice it has its own bin folder:

img_174

Which contains its own conda binary:

img_175

And python3 binary:

img_176

It also has its own lib folder:

img_177

Which has a python3.11 folder:

img_178

This contains the standard modules associated with the base Python environment. Notice there is a site-packages folder, this contains third-party libraries:

img_179

The conda folder contains the conda package manager:

img_180

The purpose of the base environment is use of the conda of the package manager. The conda package manager is used to create Python environments which are in the envs subfolder:

img_181

The spyder-runtime environment is present:

img_182

Notice spyder-runtime has its own bin subfolder:

img_183

With its own python3 binary:

img_184

Notice spyder-runtime has its own lib subfolder:

img_185

Which has a python3.11 folder which contains the Python standard modules:

img_186

And site-packages subfolder which contains third-party modules:

img_187

The numpy library is found in the numpy folder:

img_188

When imported the __init__.py is referenced:

img_189

The matplotlib library is found in the matplotlib folder. When the library is imported the __init__.py is referenced:

img_190

However normally the pyplot interface module is referenced:

img_191

Note there is no seaborn subfolder as it is not preinstalled with Spyder.

The Spyder installer is conda based, the base environment is used to update conda, which is in turn is used to update the spyder-runtime environment when there is a Spyder update available. This conda is not intended to be used by the end user.

Miniforge Installation

Miniforge is a minimal installer for conda which uses the community channel conda-forge by default. The Miniforge base environment is used only for the conda package manager and other packages are typically installed in separate Python environments. Note Anaconda/Miniconda are not recommended as they use a tainted repository anaconda by default which has commercial restrictions and older package versions which often result with incompatibilities with the current version of Spyder.

Miniforge is developed on GitHub and the latest release is on the GitHub Miniforge Releases Page. Note Mambaforge is considered obsolete and therefore the installers listed at the top should be avoided.

For Ubuntu the Miniforge3-x.xx.x-x-Linux-x86_64.sh or Miniforge3-Linux-x86_64.sh should be selected (these are the same installer):

img_192

img_193

img_194

The Downloads folder can be opened in the Terminal:

img_195

If:

bash M↹

is input:

img_196

The file name will autocomplete:

bash Miniforge3-24.11.0-1-Linux-x86_64.sh

Press to execute the script:

img_197

Press to begin scrolling through the license agreement:

img_198

Press q to quit scrolling:

img_199

To accept the license agreement input yes and press :

img_200

To install in the default location press :

img_201

A prompt to initialise conda will display. Note the default option if is input is No, which means Miniforge is installed but not initialised/

img_202

Initialisation updates the .bashrc file which are the bash recall parameters used by the Linux Terminal:

img_203

Note the Spyder installer has already updated this .bashrc file, so the binary spyder is recognised:

img_204

To initialise conda with the Terminal, input yes and press :

img_205

Miniforge is installed and initialised:

img_206

The .bashrc file is updated. If it is refreshed:

img_207

A conda initialisation block displays:

img_208

When a new Terminal instance is opened, it will look at the recall parameters and add the prefix (base), indicating the base Python environment (from Miniforge) is selected:

img_209

Initialising conda with the Linux Terminal Manually

If initialisation was not carried out, (base) will not display and the conda package manager cannot be used from the Terminal unless the directory containing the conda binary is manually input. This situation can be mimicked using:

conda init --reverse

img_210

This means the following initialisation block is not present int he .bashrc file:

img_211

img_212

To initialise Miniforge manually, navigate to th Home folder and select the Miniforge subfolder:

img_213

Then select the bin subfolder:

img_214

Right click the folder and select, Open in Terminal:

img_215

Input:

./conda init --all

The ./ means look in the same directory as the current working directory for the conda binary.

img_216

Miniforge is installed and initialised. When a new Terminal instance is opened, it will look at the recall parameters and add the prefix (base), indicating the base Python environment (from Miniforge) is selected.

img_217

Creating a Custom spyder-env Environment (conda)

The purpose of the base environment is to use the conda package manager. It is not recommended to install other packages in base:

img_218

before using the conda package manager, it should be updated to the latest version using:

conda update conda

img_219

The default channel is conda-forge which is the community channel:

img_220

conda and conda dependencies will be updated. Input y in order to proceed:

img_221

conda is now up to date:

img_222

A new environment can be created using:

conda create -n spyder-env spyder-kernels python seaborn scikit-learn pyarrow sympy openpyxl xlrd xlsxwriter lxml sqlalchemy tabulate pyqt ffmpeg ruff

This has spyder-kernels which is required for Syder to use the environment. seaborn which has numpy, pandas and matplotlib as dependencies. scikit-learn for machine learning. pyarrow, openpyxl, xlrd, xlsxwriter, lxml, sqlalchemy, tabulate for various file pandas formats. pyqt for matplotlib's interactive backend and ffmpeg for saving matplotlib animations.

-n means name and spyder-env is the name of the Python environment. Specifying an environment using -n means changes to that environment will be made opposed to base which is the currently activate environment.

img_223

These packages will all be installed from the conda-forge channel. In the spyder-env folder which is found in the envs subfolder of base:

img_224

Details about packages to be downloaded will be shown:

img_225

Input y in order to proceed:

img_226

The packages are installed in the environment but it is not activated:

img_227

To activate it use:

conda activate spyder-env

img_228

Notice the prefix is now (spyder-env) meaning this environment is activated. An ipython shell can be launched. Imports of the standard modules and third-party libraries can be carried out, if the __file__ attribute of these is checked, notice they are all found in the directory of spyder-env:

img_229

img_230

img_231

img_232

Selecting the Custom spyder-env Environment (conda)

In Spyder, the default environment spyder-runtime is selected:

img_233

Go to Tools → Preferences:

img_234

Select IPython Interpretter:

img_235

Select Use the Following Interpretter and select spyder-env (conda) from the dropdown list:

img_236

Select Apply:

img_237

Close Spyder and relaunch using the start menu shortcut or inputting:

spyder

in the Terminal.

img_238

spyder-env should be shown at the bottom and now seaborn can be imported:

import seaborn as sns

img_239

Changing Default Plot Backend

The default plot backend can be changed, by selecting Tools → Preferences:

img_240

Then IPython Console → Graphics and changing the backend to Qt:

img_241

If the following is plotted:

#%% Import Libraries
import numpy as np 
import matplotlib.pyplot as plt 
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * np.pi * np.sin(x)
#%% Plot Data
plt.plot(x, y)
plt.xlabel(R'$x$', usetex=True)
plt.ylabel(R'$2 \pi \sin{x}$', usetex=True)

img_242

In the GNOME desktop environment, when a Window title bar is right clicked, it can be set to always on top:

img_243

This allows modification and visualisation of the plot using the console.

Updating

There is a new release of Spyder, approximately every month. When available a prompt for the upgrade should display and Spyder should update using packages from conda-forge using its internal conda package manager:

If an external conda environment was created, it will need to be updated, with a compatible version of spyder-kernels. Open up the Windows Terminal an updte the conda package manager in base:

conda update conda

Then activate spyder-env and searh for updates to all packages:

conda activate spyder-env
conda update --all

Return to Python Tutorials