analitics

Pages

Friday, April 26, 2019

Python 3.7.3 and Django REST framework.

Today I tested something simpler for beginners: Django REST framework.
Once you understand how it works then it's simple to use.
This tutorial does not address the security issues generated by the REST, Django framework.
The official webpage comes with many information and technical specifications for this API:
Django REST framework is a powerful and flexible toolkit for building Web APIs.
The example I've submitted is built into the Scripts folder because I did not use the virtual environment.
Let's start installing the python module.
C:\Python373\> cd Scripts
C:\Python373\Scripts\>pip install djangorestframework
C:\Python373\Scripts\>django-admin startproject example
C:\Python373\Scripts\>cd example 
C:\Python373\Scripts\>python manage.py migrate 
C:\Python373\Scripts\>python manage.py createsuperuser
C:\Python373\Scripts\>python manage.py startapp test001
In the example folder we will make changes.
First is the settings.py file:
INSTALLED_APPS = [
...
    'rest_framework',
    'test001']
The next file is the urls.py:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('test001.urls'))
]
Also make changes in the test001 folder
You must create a python script and call it urls.py:
from django.urls import path, include

# this urlpatterns will fill later 
urlpatterns = []
You make changes to the file models.py and create a named class test.
This class will have two fields that we will update.
from django.db import models

class test(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
44/5000
The following commands will synchronize the database:
C:\Python373\Scripts\example>python manage.py makemigrations
...
  test001\migrations\0001_initial.py
    - Create model test
C:\Python373\Scripts\example>python manage.py migrate
...
Running migrations:
...
Another step is to add the test into admin.py script:
from django.contrib import admin
from .models import test
admin.site.register(test)
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
Let's create an serializers.py python script into test001 folder and use this code:
from rest_framework import serializers
from .models import test

class test_serializer(serializers.ModelSerializer):
    class Meta:
        model = test
        fields = ('id', 'first_name', 'last_name')
Also is need to update the views.py python script:
from django.shortcuts import render
from rest_framework import viewsets
from .models import test
from .serializers import test_serializer

class test_view(viewsets.ModelViewSet):
    #query to get all information from database
    queryset = test.objects.all()
    serializer_class = test_serializer
Now because is all create the last step is to fix the urls.py from test001 folder with the routers.
The REST framework adds support for automatic URL routing to Django.
from django.urls import path, include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('test001', views.test_view)
#add to path 
urlpatterns = [
    path('', include(router.urls))
]
Now you can test it with:
C:\Python373\Scripts\example>python manage.py runserver
If you want to make changes into models.py then you will need to use the commands to synchronize the database after these use"commands
makemigrations and migrate to fix errors.
If you encounter such run-time errors
"GET /static/assets/js/docs.min.js HTTP/1.1" 404 1667..."
These errors can be the result of settings like DEBUG, STATICFILES_DIRS or STATIC_ROOT from file settings.py.
Then you need to execute python manage.py collectstatic and Django goes through all directories where static files can be found and places them in your static root.
The result of this tutorial can be see on my youtube channel:

Wednesday, April 24, 2019

Google's Python Class - another step.

Here's something I like and I hope it should be known in the Python community.
Some people from Google want to attract the python community into a learning process.
Although most of the API documentation examples do not exist in the Python programming language, they have not disappeared.
Let's hope this little step will increase the chances of programming Google with the Python programming language.
This material was created by Nick Parlante working in the engEDU group at Google.
Welcome to Google's Python Class -- this is a free class for people with a little bit of programming experience who want to learn Python. The class includes written materials, lecture videos, and lots of code exercises to practice Python coding. These materials are used within Google to introduce Python to people who have just a little programming experience. The first exercises work on basic Python concepts like strings and lists, building up to the later exercises which are full programs dealing with text files, processes, and http connections. The class is geared for people who have a little bit of programming experience in some language, enough to know what a "variable" or "if statement" is. Beyond that, you do not need to be an expert programmer to use this material.
Read more about this course here.

Tuesday, April 23, 2019

Python 3.7.3 : Testing firebase with Python 3.7.3 .

The tutorial for today consists of using the Firebase service with python version 3.7.3 .
As you know Firebase offers multiple free and paid services.
In order to use the Python programming language, we need to use the pip utility to enter the required modules.
If your installation requires other python modules then you will need to install them in the same way.
C:\Python373>pip install firebase-admin
C:\Python373\Scripts>pip install google-cloud-firestore
The next step is to log in with a firebase account and create or use a project with a database.
You must use this link to see your project data and create your JSON configuration file for access.
Here's a screenshot of an old project in another programming language that I used for this tutorial.

At point 1, you will find Project Settings - Service accounts and you will need to use the Generate new private key button.
This will generate a JSON file that we will use in the python script.
Be careful to define the path to the python script file.
At point 2, you will find the database or you will need to create it to use it.
The script I'm going to present has commented on the lines for a better understanding of how to use it.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# the go-test.json from my project settings 
cred = credentials.Certificate("go-test.json")

# start using firebase python modules 
firebase_admin.initialize_app(cred)

# access the database
database = firestore.client()

# access the collection with limit 
my_ref = database.collection("test").limit(2)

# show the values from database
try:
    docs = my_ref.stream()
    for doc in docs:
         print(u'Doc Data:{}'.format(doc.to_dict()))
except:
    print(u'Missing data')

# result running
#Doc Data:{'nrcrt': 1, 'string_value': 'this is a text'}
#Doc Data:{'name': 'test', 'added': 'just now'}

# add data to database
my_ref_add = database.collection("test")
my_ref_add.add({u'nickname': u'catafest', u'friend': u'Last Ocelot'})

# show the new database values
try:
    docs = my_ref_add.stream()
    for doc in docs:
         print(u'Doc Data:{}'.format(doc.to_dict()))
except:
    print(u'Missing data')

# result running
#Doc Data:{'nrcrt': 1, 'string_value': 'this is a text'}
#Doc Data:{'friend': 'Last Ocelot', 'nickname': 'catafest'}
#Doc Data:{'name': 'test', 'added': 'just now'}

# get just one 
doc = database.collection('test').document('doc_id').get()

# show create time 
print(doc.create_time)

# result running
#seconds: 1556014478
#nanos: 460439000

Thursday, April 18, 2019

About psychopy tool.

A good definition for this tool can be found at the Wikipedia website:
2002: PsychoPy was originally written by Peirce as a proof of concept - that a high-level scripting language could generate experimental stimuli in real time (existing solutions, such as Psychtoolbox, had to pre-generate movies or use CLUT animation techniques).
The install of this python module is very simple:
C:\Python373\Scripts>pip install psychopy
Using this command to start this tool:
C:\Python373>psychopy
The tool starts with two graphical interfaces:
  • one for Coder area;
  • one for the project with an untitled.psyexp;
Let's see one screenshot with this tool:

This open source tool, written in the Python programming language, help you to run a wide range of neuroscience, psychology and psychophysics experiments.
I searched the internet for the capabilities of this tool and the obvious conclusion is a utility for building experiments with a wide range of applicability.
This tool lets you use the pavlovia website, see more:
Pavlovia is a place for the wide community of researchers in the behavioural sciences to run, share, and explore experiments online.
This tool used commonly-used components for linguistic experiments:
  1. Text Component (display text on the screen);
  2. Sound Component (play sounds);
  3. Keyboard Component (receive input from the keyboard);
  4. RatingScale Component (collect a numeric rating or a choice from a few alternatives, via the mouse, the keyboard or both);
  5. Code Component (insert short pieces of python code into your experiments (e.g. time stamp for the production task);
The easy way is to use the Builder tool to generate a wide range of experiments easily from the Builder using its intuitive, graphical user interface (GUI).
Today I will use the Coder with programming a simple example.
To access demos, you need to create a python script in the Coder area (use File menu - New) then use the Demos from the application menu.
Everything in a PsychoPy experiment needs a unique name.
The name must contain only letters, numbers and underscores and not contain spaces, punctuation or mathematical symbols.
This tool saves several data files: a Microsoft Excel (spreadsheet) file, a psydat file, and a log file.
The example I used today for this tutorial is how to import from a CSV file named colors_001.csv and used with psychopy python module to create stimuli:
3.3;"red"
1.1;"green"
4.4;"red"
2.2;"green"
This python script named colors.py I used to import the CSV file and use it:
from psychopy import core, visual, event
import csv
  
## Setup section, read experiment variables from file
win = visual.Window([400,300], monitor="testMonitor", units="cm", fullscr=False)
stimuli = []
datafile = open("colors_001.csv", "r",encoding="utf8")
reader = csv.reader(datafile, delimiter=";")
for row in reader:
    if len(row)==2:         # ignore empty and incomplete lines
        size = float(row[0])  # the first element in the row converted to a floating point number
        color = row[1]        # the second element in the row
        stimulus = visual.Rect(win, width=size, height=size)
        stimulus.fillColor = color
        stimuli.append(stimulus)
datafile.close()
  
## Experiment Section, use experiment variables here
for stimulus in stimuli:
    stimulus.draw()
    win.flip()
    core.wait(1.000)

## Closing Section
win.close()
core.quit()
The result of this script will show you four squares colored by the CSV file.
If you don't like to use the Builder or Coder areas, then you can simply use the python:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from psychopy import visual, core
pygame 1.9.5
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> win = visual.Window()
>>> msg = visual.TextStim(win, text=u"Hello python users!")
>>> msg.draw()
>>> win.flip()
47.541564770566765
The output will be a window with a text message.

Wednesday, April 17, 2019

Update python modules of 3.73 version.

Today we tested an older tool with the new version of python 3.7.3.
This is a tool that will help you update your python modules.
Here's how to install:
C:\Python373\Scripts>pip install pip-review
Collecting pip-review
...
Requirement already satisfied: pyparsing>=2.0.2 in c:\python373\lib\site-package
s (from packaging->pip-review) (2.4.0)
Installing collected packages: packaging, pip-review
Successfully installed packaging-19.0 pip-review-1.0
Here is the complete overview of the options.
C:\Python373\Scripts>pip-review -h
usage: pip-review [-h] [--verbose] [--raw] [--interactive] [--auto]

Keeps your Python packages fresh.

optional arguments:
  -h, --help         show this help message and exit
  --verbose, -v      Show more output
  --raw, -r          Print raw lines (suitable for passing to pip install)
  --interactive, -i  Ask interactively to install updates
  --auto, -a         Automatically install every update found

Unrecognised arguments will be forwarded to pip list --outdated, so you can
pass things such as --user, --pre and --timeout and they will do exactly what
you expect. See pip list -h for a full overview of the options.
To update all python modules you can use:
C:\Python373\Scripts>pip-review --auto
To run interactively, you can ask to upgrade for each package:
C:\Python373\Scripts>pip-review --interactive


Monday, April 15, 2019

Using the ORB feature from OpenCV python module.

Today I will show you a simple script using the ORB (oriented BRIEF), see C++ documentation / OpenCV.
The algorithm uses FAST in pyramids to detect stable keypoints, selects the strongest features using FAST or Harris response, finds their orientation using first-order moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or k-tuples) are rotated according to the measured orientation).
One good feature of ORB is the is rotation invariant and resistant to noise.
The ORB descriptor use the Center of the mass of the patch of the Moment (sum of x,y), Centroid (the result of the matrix of all moment) and Orientation ( the atan2 of moment one and two).
One good article about ORB can be found here.
Let's see the script code of this python example:
import cv2
import numpy as np 

image_1 = cv2.imread("1.png", cv2.IMREAD_GRAYSCALE)
image_2 = cv2.imread("2.png", cv2.IMREAD_GRAYSCALE)

orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(image_1,None)
kp2, des2 = orb.detectAndCompute(image_2,None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key = lambda x:x.distance)

matching_result = cv2.drawMatches(image_1, kp1, image_2, kp2, matches[:150], None, flags=2)

cv2.imshow("Image 1", image_1)
cv2.imshow("Image 2", image_2)
cv2.imshow("Matching result", matching_result)
cv2.waitKey(0)
cv2.destroyAllWindows()
The script use two file images 1.png and 2.png.
The result is an image composed of the two on which the areas of similitude are traced as detected by the mathematical algorithm.

Sunday, April 14, 2019

Using the python module music21.

What is music21?
Music21 is a set of tools for helping scholars and other active listeners answer questions about music quickly and simply. If you’ve ever asked yourself a question like, “I wonder how often Bach does that” or “I wish I knew which band was the first to use these chords in this order,” or “I’ll bet we’d know more about Renaissance counterpoint (or Indian ragas or post-tonal pitch structures or the form of minuets) if I could write a program to automatically write more of them,” then music21 can help you with your work.
This toolkit for Computer-Aided Musical Analysis was developed at MIT by cuthbertLab. Michael Scott Cuthbert, Principal Investigator.
The development of music21 is supported by the generosity of the Seaver Institute and the NEH.
The tutorial today is about the python music21 module.
Let's start with the default pip tool to install this python module:
C:\Python364\Scripts>pip install --upgrade music21
Collecting music21
...
  Running setup.py install for music21 ... done
Successfully installed music21-5.5.0
The next step tells us to install some additional python modules:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from music21 import * 
music21: Certain music21 functions might need these optional packages: matplotlib,
 scipy;
if you run into errors, install them by following the instructions at
http://mit.edu/music21/doc/installing/installAdditional.html
Let's install these python modules:
C:\Python373\Scripts>pip install matplotlib
C:\Python373\Scripts>pip install scipy
Let's test and play a simple example (Bach’s BWV 66.6):
>>> from music21 import *
>>> s = corpus.parse('bwv66.6')
>>> sChords = s.chordify()
>>> sChords
...
>>> sChords.show('midi')
If you want to save it, use:
>>> sChords.write("midi", "bach6.mid")
'bach6.mid'
Another example is to play a note on guitar (C#):
from music21 import stream, instrument
from music21.note import Note
cd = Note("C#", type='quarter')
test = stream.Part()
test.insert(0, instrument.AcousticGuitar())
test_measure = stream.Measure()
test_measure.append(cd)
test.append(test_measure)
test.show('midi')
You can see all the instruments here.
This python module is very complex and can be used with additional software, see here.
More details can be found in the documentation.

Friday, April 12, 2019

Using pytineye to automate searching for images.

The TinEye API is ideally suited for image and profile verification, UGC moderation, copyright compliance and fraud detection.
Read more about the TinEye API here.
You need to use authentication for this API, read here.
To use the TinEye API you must purchase a search bundle.
The documentation for Python can be found here.
Let's start with the installation.
You need to download the zip file from GitHub and install using the pip tool:
C:\Python373\Scripts>pip3.7.exe install pytineye-master.zip
...
Successfully installed pytineye-1.3

>>> import pytineye
>>> from pytineye import TinEyeAPIRequest
>>> myapi = TinEyeAPIRequest('http://api.tineye.com/rest/', 'your_public_key', 'your_private_key')
>>> myapi.remaining_searches()
{'bundles': [], 'total_remaining_searches': 0}
Because I don't have search the python code return an error:
>>> myapi.search_url(url='http://en.es-static.us/upl/2019/03/rogue-planet-CFBD-S
IR-J214947.2-040308.9-2012-800x450.jpg')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python373\lib\site-packages\pytineye\api.py", line 304, in search_url

    obj = self._request('search', params, **kwargs)
  File "C:\Python373\lib\site-packages\pytineye\api.py", line 276, in _request
    raise TinEyeAPIError(obj['code'], obj.get('messages'))
pytineye.exceptions.TinEyeAPIError: APIError:
                   code    = 401
                   message = ['AUTHORIZATION_ERROR', 'You have no more searches
available. Please purchase another bundle if you wish to make more searches.']
If you want to buy TinEye API searches then the prices start from:
5,000 searches $200.00 USD($0.04 per search)
10,000 searches $300.00 USD($0.03 per search)
50,000 searches $1,000.00 USD($0.02 per search)
1,000,000 searches $10,000.00 USD($0.01 per search)

Friday, April 5, 2019

First test with 3.7.3 and opencv-python module version 4.0.0 .

The Python 3.7.3 is the third maintenance release of Python 3.7 and is released at March 25, 2019.
More about this new released version can be found at official website.
C:\Python373\Scripts>pip install opencv-python
Collecting opencv-python
...
Installing collected packages: numpy, opencv-python
Successfully installed numpy-1.16.2 opencv-python-4.0.0.21
Let's test it:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.0.0'
Let test a simple example that computes a dense optical flow using the Gunnar Farneback’s algorithm.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255
while(1):
    ret, frame2 = cap.read()
    next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
    flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.1, 1, 2, 3, 5, 11.2, 0)
    mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
    hsv[...,0] = ang*180/np.pi/2
    hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
    bgr = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)
    cv2.imshow('frame2',bgr)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    prvs = next
cap.release()
cv2.destroyAllWindows()

Wednesday, April 3, 2019

About Ninja IDE for python programming.

This I.D.E. is a very good tool for python programming and development.
The version of this tool is 2.3.
I tested with my Django project on Windows OS and works great.
The development team comes with this info:
NINJA-IDE (from the recursive acronym: "Ninja-IDE Is Not Just Another IDE"), is a cross-platform integrated development environment (IDE). NINJA-IDE runs on Linux/X11, Mac OS X and Windows desktop operating systems, and allows developers to create applications for several purposes using all the tools and utilities of NINJA-IDE, making the task of writing software easier and more enjoyable.
The official webpage can be found here.
If you want to use it with Django the easy way is to install the plugin for this area.
You can see all about the development team about page.

Saturday, March 30, 2019

Testing the python IMDbPY module with simple commands.

Today we tested a more innovative but useful method with python aaa mode.
The main reason I used this method is the lack of documentation.
Using this method, we have reached elements related to the use of reported methods and errors.
The test was done on a Fedora 29 Linux system with a classic install with the pip utility:
[mythcat@desk ~]$ pip install imdbpy --user
Collecting imdbpy
...
Successfully installed SQLAlchemy-1.3.1 imdbpy-6.6 
I used an example of a person's search in the IMDB database to test this method.
>>> from imdb import IMDb, IMDbError
>>> try:
...     im=IMDb()
...     people = im.search_person('Mel Gibson')
... except IMDbError as exc:
...     print(exc) 
Using the dir and print function will show the resulting output configuration and will have the following form:
>>> print(people)
[, , , , , , , , , , , , , , , , , , , ] 
I have used the dir function for a relative view of the options we have:
>>> print(dir(people))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', 
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', 
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', 
'__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> print(dir(people[0]))
['_Container__role', '__bool__', '__class__', '__contains__', '__deepcopy__', '__delattr__', 
'__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_additional_keys', '_clear', 
'_get_currentRole', '_get_roleID', '_getitem', '_image_key', '_init', '_reset', '_roleClass', 
'_roleIsPerson', '_set_currentRole', '_set_roleID', 'accessSystem', 'add_to_current_info', 
'append_item', 'asXML', 'billingPos', 'charactersRefs', 'clear', 'cmpFunct', 'copy', 'currentRole', 
'current_info', 'data', 'default_info', 'get', 'getAsXML', 'getID', 'get_charactersRefs', 
'get_current_info', 'get_fullsizeURL', 'get_namesRefs', 'get_titlesRefs', 'has_current_info', 
'has_key', 'infoset2keys', 'isSame', 'isSameName', 'isSamePerson', 'items', 'iteritems', 
'iterkeys', 'itervalues', 'key2infoset', 'keys', 'keys_alias', 'keys_tomodify', 'keys_tomodify_list', 
'modFunct', 'myID', 'myName', 'namesRefs', 'notes', 'personID', 'pop', 'popitem', 'reset', 'roleID', 
'set_current_info', 'set_data', 'set_item', 'set_mod_funct', 'set_name', 'setdefault', 'summary', 
'titlesRefs', 'update', 'update_charactersRefs', 'update_infoset_map', 'update_namesRefs', 
'update_titlesRefs', 'values']
Here are some simple examples of displaying using the print function to view content in output:

>>> print(people[0].values())
[u'Catalin', u'II', u'Catalin', u'Catalin (II)', u'Catalin (II)']
>>> print(people[0].data)
{u'name': u'Catalin', u'imdbIndex': u'II'}
>>> print(people[1].data.viewitems())
dict_items([(u'name', u'Moreno, Catalina Sandino')])
>>> print(people[1].data.values())
[u'Moreno, Catalina Sandino']
>>> print(people[0].getID())
2165704
>>> print(people[0].itervalues())
The built-in function iter takes an iterable object and returns an iterator.
>>> print(people[0].itervalues().next())
Catalin
>>> print(people[0].asXML()) 
The last line of code will return XML content.
This simple example simply illustrates how to access structured information through simple Python commands.

Saturday, March 23, 2019

Fix errors with the python errors encyclopedia.

Today I will present a website that I find very useful in learning and developing with the Python programming language.
This very short tutorial it is very useful for newcomers to get rid of all sorts of common questions about certain errors.
I encounter these types of errors when using stackoverflow account and can be a time consuming for most people who use it.
Try to read all about these errors on the python errors encyclopedia.

Wednesday, March 20, 2019

Using multiprocessing - a simple introduction.

The multiprocessing module was added to Python in version 2.6 and can be used with new python versions.
It was originally defined in PEP 371 by Jesse Noller and Richard Oudkerk.
The multiprocessing package also includes some APIs that are not in the threading module at all.
Python introduced the multiprocessing module to let us write parallel code.
You can use three basic classes: Process, Queue, and Lock, which will help you build a parallel program.
For more details, you can check the documentation of this python module.
Today, I will present in this tutorial two examples that highlight how to work with this python module.
The most basic approach is probably to use the Process class.
The Process class is very similar to the threading module’s Thread class.
It is also necessary to use the Manager because is responsible for coordinating shared information.
The source code is simple to understand and is commented on to see the intermediate steps.
Let's start with the first example that uses a function of adding two numbers in two processes.
import multiprocessing

def sum(a,b):
 t=a+b
 print ("sum is:",t)

if __name__ == '__main__':
 # create process processing_001 with target function and args of the target function
 processing_001 = multiprocessing.Process(target=sum, args=(7,6))
 processing_002 = multiprocessing.Process(target=sum, args=(1,1))
 # starting processing_001
 processing_001.start()
 # starting processing_002
 processing_002.start()
 #processes are started
 # stop processing_001 until is complete with join
 processing_001.join()
 # stop processing_002 until is complete with join
 processing_001.join()
 # result is C:\Python364>python.exe multiprocessing_001.py
 #sum is: 13
 #sum is: 2
The second example solves the next problem of the engineer who checks the speed of accomplishment of the tasks performed by two robots.
Three processes are created for each: robots and engineer.
All these processes are completed in the same dictionary resource using the Manager.
For each task performed by the robot (start/join processes), the robot finds a random execution rate (function random.random) that is then added to the result (result) with the robot name and execution speed.
Let's see the source code and the result:
import multiprocessing 
from multiprocessing import Process, Manager
import os
import random

def robot1(result):
 print("robot1 has ID process: {}".format(os.getpid()))
 speed_robot1=random.random()
 result["robot1"] = speed_robot1
 print ("worker speed tasks:",speed_robot1)
 #print (result)
 
def robot2(result):
 print("robot2 has ID process: {}".format(os.getpid()))
 speed_robot2=random.random()
 result["robot2"] = speed_robot2
 print ("worker speed tasks:",speed_robot2)
 #print (result)
 
def engineer(result):
 print("engineer has ID process: {}".format(os.getpid()))
 for key, value in result.items():
  print("Result: {}".format((key, value)))
 # you can add code to sort the values and print 
 # for key, value in sorted(result.items()):
 # print("Result: {}".format((key, value)))
 
if __name__ == '__main__':
 # show the main process
 print("the main ID process: {}". format(os.getpid()))
 # create a share dictionary resouce 
 manager = multiprocessing.Manager()
 result = manager.dict()
 # the process starts for  robot1
 ro1 = multiprocessing.Process(target=robot1, args=(result,))
 ro1.start()
 # the process starts for  robot2
 ro2 = multiprocessing.Process(target=robot2, args=(result,))
 ro2.start()
 # stops the robot1 process
 ro1.join()
 # stops the robot2 process
 ro2.join()
 # create the engineer process
 en = multiprocessing.Process(target=engineer, args=(result,))
 # start the process for the engineer
 en.start()
 # stops the engineer's process
 en.join()
The result is:
C:\Python364>python.exe multiprocessing_002.py
the main ID process: 7816
robot1 has ID process: 6476
worker speed tasks: 0.48279764083908094
robot2 has ID process: 7560
worker speed tasks: 0.44408591959008503
engineer has ID process: 7000
Result: ('robot1', 0.48279764083908094)
Result: ('robot2', 0.44408591959008503)