analitics

Pages

Friday, October 26, 2018

Python Qt5 : MP3 player example.

This tutorial with PyQt5 will allow us to play an MP3 file using QtMultimedia.
I used a test.mp3 file in the same folder with my python script.
This is the source script:
import sys

from PyQt5 import QtCore, QtWidgets, QtMultimedia

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    filename = 'test.mp3'
    fullpath = QtCore.QDir.current().absoluteFilePath(filename) 
    media = QtCore.QUrl.fromLocalFile(fullpath)
    content = QtMultimedia.QMediaContent(media)
    player = QtMultimedia.QMediaPlayer()
    player.setMedia(content)
    player.play()
    sys.exit(app.exec_())

Wednesday, October 24, 2018

Python Qt5 : Webcam example.

Today I come with another source code.
This example uses QtMultimedia to create use of the webcam.
The source code follows the steps from finding, set and use a webcam.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

import os
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.online_webcams = QCameraInfo.availableCameras()
        if not self.online_webcams:
            pass #quit
        self.exist = QCameraViewfinder()
        self.exist.show()
        self.setCentralWidget(self.exist)

        # set the default webcam.
        self.get_webcam(0)
        self.setWindowTitle("WebCam")
        self.show()

    def get_webcam(self, i):
        self.my_webcam = QCamera(self.online_webcams[i])
        self.my_webcam.setViewfinder(self.exist)
        self.my_webcam.setCaptureMode(QCamera.CaptureStillImage)
        self.my_webcam.error.connect(lambda: self.alert(self.my_webcam.errorString()))
        self.my_webcam.start()

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("WebCam")

    window = MainWindow()
    app.exec_()

Tuesday, October 23, 2018

Python Qt5 : toolbar example.

This is a simple example with PyQt5 python module and python 3.6.4 version.
The example is about how to create a toolbar with PyQt5.
The base of this source code is the create a default window application.
I create a toolbar and I add an action to this toolbar.
The name of the toolbar is my_toolbar.
The action is named one_action.
This action is linked to a python function named action_one.
I add to my source code another function named alert.
This is good for debugging part to handle with errors and displaying alerts.
Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        my_toolbar = QToolBar("toolbar")
        my_toolbar.setIconSize(QSize(48, 48))
        self.addToolBar(my_toolbar)
        
        one_action = QAction(QIcon(), "Action one", self)        
        one_action.setStatusTip("Action one on toolbar")
        one_action.triggered.connect(self.action_one)
        my_toolbar.addAction(one_action)
        
        self.setWindowTitle("Window PyQt5 - 001")
        self.show()

    def action_one(self):
        print("Action one")

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("Window PyQt5 - 001")

    window = MainWindow()
    app.exec_()

Sunday, October 21, 2018

OpenGL and OpenCV with python 2.7 - part 006.

Today I deal with a simple example about how to use your webcam like a python module.
This will allow you to make your python module for your webcam.
My reason was to make a good webcam module to work with python modules like OpenCV and OpenGL and webcam devices.
The source code is simple and has just three functions: start, _update_frame and get_current_frame.
You can make more functions into this python module named webcam.
import cv2
from threading import Thread
  
class webcam:
  
    def __init__(self):
        self.video_capture = cv2.VideoCapture(0)
        self.current_frame = self.video_capture.read()[1]
          
    # create thread for capturing images
    def start(self):
        Thread(target=self._update_frame, args=()).start()
  
    def _update_frame(self):
        while(True):
            self.current_frame = self.video_capture.read()[1]
                  
    # get the current frame
    def get_current_frame(self):
        return self.current_frame
I make also a python script to test this python module:
from webcam import webcam
import cv2
 
dir(webcam)
cam = webcam()
cam.start()
 
while True:
     
    # get image from webcam
    image = cam.get_current_frame()

The shutil python module.

The shutil module helps you to accomplish tasks, such as: copying, moving, or removing directory trees.
This python script creates a zip file in the current directory containing all contents of dir and then clears dir.

import shutil
from os import makedirs

def zip(out_fileName, dir):
shutil.make_archive(str(out_fileName), 'zip', dir)
shutil.rmtree(dir)
makedirs(dir[:-1])

The scapy python module - part 002.

This is another python tutorial about scapy python module.
The last was made on Linux and now I used Windows 10 OS.
Let's install this python module with python version 2.7.13 and pip.
C:\>cd Python27

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install scapy
Collecting scapy
  Downloading scapy-2.3.3.tgz (1.4MB)
    100% |################################| 1.4MB 736kB/s
  In the tar file c:\users\mythcat\appdata\local\temp\pip-26vi9x-unpack\scapy-2.3.3.tgz 
the member scapy-2.3.3/README is invalid: unable to resolve link inside archive
Installing collected packages: scapy
  Running setup.py install for scapy ... done
Successfully installed scapy-2.3.3
The next step is to deal with
C:\Python27\Scripts>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scapy
>>> from scapy import *
>>> dir(scapy)
['VERSION', '_SCAPY_PKG_DIR', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
 '__path__', '_version', '_version_from_git_describe', 'base_classes', 'config', 'dadict', 'data',
 'error', 'os', 'plist', 'pton_ntop', 're', 'subprocess', 'supersocket', 'themes', 'utils', 
'with_statement']

This is not working on WINDOWS

Using PyUSB with python 3.x .

C:\Python34\Scripts>pip3.4.exe install PyUSB
Downloading/unpacking PyUSB
  Running setup.py (path:C:\Users\mythcat\AppData\Local\Temp\pip_build_mythcat\PyUSB\setup.py) 
egg_info for package PyUSB

Installing collected packages: PyUSB
  Running setup.py install for PyUSB

Successfully installed PyUSB
Cleaning up...
Now you need to install this filter from here.
If not, you can get errors like this: raise NoBackendError('No backend available')
usb.core.NoBackendError: No backend available
Let's make a simple test example:
import usb.core
import usb.util
import sys

class find_class(object):
    def __init__(self, class_):
        self._class = class_
    def __call__(self, device):
        # first, let's check the device
        if device.bDeviceClass == self._class:
            return True
        # ok, transverse all devices to find an
        # interface that matches our class
        for cfg in device:
            # find_descriptor: what's it?
            intf = usb.util.find_descriptor(
                                        cfg,
                                        bInterfaceClass=self._class
                                )
            if intf is not None:
                return True

        return False

all = usb.core.find(find_all=1, custom_match=find_class(7))
print (all)
And show the result:
C:\Python34>python.exe usb_devs.py
< generator 0x0000000003d8d5e8="" at="" device_iter="" object="" >

The ansible python module - part 001.

Ansible is an IT automation tool.
It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates.
First, you need to install the VCForPython27.
Install now the pycrypto python module:
C:\Python27\Scripts>pip install  --upgrade  --trusted-host  pypi.python.org pycrypto
Collecting pycrypto
  Downloading pycrypto-2.6.1.tar.gz (446kB)
    100% |################################| 450kB 3.8MB/s
Installing collected packages: pycrypto
  Running setup.py install for pycrypto ... done
Successfully installed pycrypto-2.6.1

C:\Python27\Scripts>pip install --trusted-host pypi.python.org ansible
Collecting ansible
Downloading ansible-2.3.0.0.tar.gz (4.3MB)
100% |################################| 4.3MB 365kB/s
Requirement already satisfied: jinja2 in c:\python27\lib\site-packages (from ansible)
Collecting PyYAML (from ansible)
...
Installing collected packages: ansible
  Running setup.py install for ansible ... done
Successfully installed ansible-2.3.0.0

Programmer's Notepad - free editor with PyPN python module.

Programmer's Notepad is a free, open source, text editor with special features for coders.
This editor comes with a variety of text clips representing common programming languages.
I saw 43 of text clips to start your programming.
Featuring
Syntax highlighting
Text Clips for simple text insertion
Code folding / outlining
Flexible Regular Expression support
Code navigation using Ctags
Projects for navigating large code bases
Extend using Python or C++
For example, if you start with the HTML then every tag will autocomplete with the end tag.
You can install the PyPN python module and used with this editor:
C:\Python364\Scripts>pip install PyPN
Collecting PyPN
...
Installing collected packages: PyPN
Successfully installed PyPN-0.9
More about PyPN module can be found here.
You can donate to support the project.