analitics

Pages

Tuesday, June 18, 2019

Python 3.7.3 : Using getters and setters in object-oriented.

The main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
Let's start with a simple example.
I created a class named my_class init with one variable named my_variable:
self._my_variable = my_variable
A new, initialized instance can be obtained by this line of code:
test_it = my_class()
The example use getter and setter methods to use this variable.
C:\Users\catafest>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class my_class:
...     def __init__(self, my_variable = 0):
...          self._my_variable = my_variable
...
...     # getter method
...     def get_my_variable(self):
...         return self._my_variable
...
...     # setter method
...     def set_my_variable(self, x):
...         self._my_variable = x
...
>>> test_it = my_class()
>>> test_it.set_my_variable(1976)
>>> print(test_it.get_my_variable())
1976
>>> print(test_it._my_variable)
1976
In Python property() is a built-in function that creates and returns a property object.
Python has four arguments property: fget, fset, fdel, doc.
  • fget is a function for retrieving an attribute value;
  • fset is a fuction for setting an attribute value;
  • fdel is a function for deleting an attribute value;
  • doc creates a docstring for attribute.
This line of code will setting the my_variable using setter:
test_it.set_my_variable(1976)
This line of code will retrieving my_variable using getter:
print(test_it.get_my_variable())
A property object has three methods, getter(), setter(), and delete() to specify fget, fset and fdel individually.
How my example changes it:
>>> class my_class:
...      def __init__(self):
...           self._my_variable = 0
...
...      # function to get value of _my_variable
...      def get_my_variable(self):
...          print("getter method called")
...          return self._my_variable
...
...      # function to set value of _my_variable
...      def set_my_variable(self, a):
...          print("setter method called")
...          self._my_variable = a
...
...      # function to delete _my_variable attribute
...      def del_my_variable(self):
...          del self._my_variable
...
...      my_variable = property(get_my_variable, set_my_variable, del_my_variabl
e)
...
>>> test_it = my_class()
>>> test_it.my_variable = 1976
setter method called
>>> print(test_it.my_variable)
getter method called
1976
Using decorator with python @property is one of the built-in decorators.
The main purpose of any decorator is to change your class methods or attributes.
The user of your class no need to make any change in their code.
This is the final result:
>>> class my_class:
...      def __init__(self):
...           self._my_variable = 0
...
...      # using property decorator
...      # a getter function
...      @property
...      def my_variable(self):
...          print("getter method called")
...          return self._my_variable
...
...      # a setter function
...      @my_variable.setter
...      def my_variable(self, my_out):
...          if(my_out < 1976):
...             raise ValueError("... this my_variable has a criteria!!")
...          print("setter method called")
...          self._my_variable = my_out
...
>>> test_it = my_class()
>>> test_it.my_variable = 1979
setter method called
>>> print(test_it.my_variable)
getter method called
1979
>>> test_it.my_variable = 1975
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 16, in my_variable
ValueError: ... this my_variable has a criteria!!
This last example show you how to use @property decorator to create getters and setters in pythonic way.

Monday, June 17, 2019

Python Qt5 : the most simple QTreeWidget - part 002.

This tutorial uses PyQt5 and Python version 3.7.3.
Let's install the PyQt5 python module with the pip tool:
C:\Python373\Scripts>pip install PyQt5
Collecting PyQt5
...
Successfully installed PyQt5-5.12.2 PyQt5-sip-4.19.17
Let's see one simple example with comments about how to use QTreeWidget.
import sys
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QApplication, QWidget

if __name__ == '__main__':
    # create a empty my_app application
    my_app = ''
    # test this my_app to create instance
    if QApplication.instance() != None:
        my_app = QApplication.instance()
    else:
        my_app = QApplication(sys.argv)
    # create a QTreeWidgetItem with tree columns
    my_tree= QTreeWidgetItem(["Column A", "Column B", "Column C"])
    # add date using a for loop 
    for i in range(6):
        list_item_row = QTreeWidgetItem(["Child A-" + str(i), "Child B-" + str(i), "Child C-" + str(i)])
        my_tree.addChild(list_item_row)
    # create my_widget widget
    my_widget = QWidget()
    my_widget.resize(640, 180)
    # create a QTreeWidget named my_tree_widget 
    my_tree_widget = QTreeWidget(my_widget)
    # set the size
    my_tree_widget.resize(640, 180)
    # set the number of columns 
    my_tree_widget.setColumnCount(3)
    # add labels for each column 
    my_tree_widget.setHeaderLabels(["Column A label", "Column B label", "Column C label"])
    # add my_tree using addTopLevelItem
    my_tree_widget.addTopLevelItem(my_tree)
    # show the widget
    my_widget.show()
    # the exit of my_app
    sys.exit(my_app.exec_())
This is another simple example written in a simple way to show how versatile are Python and PyQt5.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTreeWidget, QTreeWidgetItem
 
my_app = QApplication(sys.argv)
my_window = QWidget()
my_layout = QVBoxLayout(my_window)
 
my_tree = QTreeWidget()
my_tree.setHeaderLabels(['Name', 'Cost ($)'])
my_item_root = QTreeWidgetItem(my_tree, ['Romania', '238,397 kmp'])
my_item_raw = QTreeWidgetItem(my_item_root, ['Black Sea', '436,402 kmp'])
 
my_layout.addWidget(my_tree)
my_window.show()
sys.exit(my_app.exec_())
If you like my simple tutorials then you subscribe or you can search my other web sites too.

Sunday, June 16, 2019

Python 3.7.3 : Using the pycryptodome python module.

This python module can be used with python 3.
More information can be found here.
PyCryptodome is a self-contained Python package of low-level cryptographic primitives.
It supports Python 2.6 and 2.7, Python 3.4 and newer, and PyPy.

The install of this python module is easy with pip tool:
C:\Python373\Scripts>pip install pycryptodome
Collecting pycryptodome
...
Installing collected packages: pycryptodome
Successfully installed pycryptodome-3.8.2
All packages from this python module are:
  • Cipher;
  • Signature;
  • Hash;
  • Publickey;
  • Protocol;
  • IO;
  • Random and Util;
Let start with a few examples:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from Crypto.Random import get_random_bytes
>>> key16 = get_random_bytes(16) # 16 bytes * 8 = 128 bits (1 byte = 8 bits)
The python module comes with features for encryption and dencryption, like RSA, AES, DES and many options.
Another good feature is KDF with PBKDF2 function:
>>> from Crypto.Protocol.KDF import PBKDF2
>>> center = b'go'
>>> password = 'go'
>>> output = PBKDF2(password, center, dkLen=64)
>>> print(output)
b'E\x0b\x91\x87\xde\xb2E\xe5Gv\x03\x86fVe8\x1e%\xb5l\xa0\xdb\xbfI\x01\xb5\xdf\x8
1\xad\x82@\x00\xacr\xc7\xa26\xc6\xe92\x1e\xf8\xe9\x0b\x9e\x93\x1dj\x1c\xff\x1c4\
xc2\x0e6\xc2\x8eYc2N\x995\x87'
>>>
If you are a fan of encryption and decryption math, then this module will enable you to use it.
By studying this module you can give a more in-depth view of what exists in this field and what does not exist.

Saturday, June 8, 2019

Python 3.7.3 : Testing the PyX python module.

This python module has a good documenation with many examples, see the eofficial wepage.
The development team come with this intro:
Summary
PyX is a Python package for the creation of PostScript, PDF, and SVG files. It combines an abstraction of the PostScript drawing model with a TeX/LaTeX interface. Complex tasks like 2d and 3d plots in publication-ready quality are built out of these primitives.
Features
  • PostScript, PDF, and SVG output for device independent, freely scalable figures;
  • seamless TeX/LaTeX integration;
  • full access to PostScript features like paths, linestyles, fill patterns, transformations, clipping, bitmap inclusion, etc.;
  • advanced geometric operations on paths like intersections, transformations, splitting, smoothing, etc.;
  • sophisticated graph generation: modular design, pluggable axes, axes partitioning based on rational number arithmetics, flexible graph styles, etc.
Let's install this python module with pip tool:
C:\Python373\Scripts>pip install PyX
...
Installing collected packages: PyX
Successfully installed PyX-0.14.1
I try few examples from official webpage and working well.
>>> from pyx import *
>>>
>>> c = canvas.canvas()
>>> c.stroke(path.line(0, 0, 3, 0))
>>> c.stroke(path.rect(0, 1, 1, 1))
>>> c.fill(path.circle(2.5, 1.5, 0.5))
>>> c.writeEPSfile("path")
>>> c.writePDFfile("path")
>>> c.writeSVGfile("path")
>>> from pyx import *
>>>
>>> c = canvas.canvas()
>>> c.stroke(path.curve(0, 0, 0, 4, 2, 4, 3, 3),
...          [style.linewidth.THICK, style.linestyle.dashed, color.rgb.blue,
...           deco.earrow([deco.stroked([color.rgb.red, style.linejoin.round]),
...                        deco.filled([color.rgb.green])], size=1)])
>>> c.writeEPSfile("arrow")
>>> c.writePDFfile("arrow")
>>> c.writeSVGfile("arrow")
I got some error from writePDFfile with this example:
>>> c.writeEPSfile("textalongpath")
>>> c.writePDFfile("textalongpath")
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python373\lib\site-packages\pyx\canvas.py", line 50, in wrappedindocu
ment
    return method(d, file, **write_kwargs)
  File "C:\Python373\lib\site-packages\pyx\document.py", line 193, in writePDFfi
le
    pdfwriter.PDFwriter(self, f, **kwargs)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 321, in __init__
    registry.write(file, self, catalog)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 78, in write
    object.write(file, writer, self)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 248, in write
    file.write("/MediaBox [%f %f %f %f]\n" % self.PDFcontent.bbox.highrestuple_p
t())
  File "C:\Python373\lib\site-packages\pyx\bbox.py", line 112, in highrestuple_p
t
    raise ValueError("Cannot return high-res tuple for empty bbox")
ValueError: Cannot return high-res tuple for empty bbox
>>> c.writeSVGfile("textalongpath")
This python module has problem with some complex example from official webpage.

Monday, June 3, 2019

Python 3.7.3 : Working with wikipedia python module.

Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia.
Let's install it:
C:\Python373\Scripts>pip install wikipedia
First, let's test the default example:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wikipedia
>>> print(wikipedia.summary("Wikipedia"))
...
.Wikipedia has been criticized for exhibiting systemic bias, for presenting a m
ixture of "truths, half truths, and some falsehoods", and for being subject to m
anipulation and spin in controversial topics. But by 2017, Facebook announced th
at it would help readers detect fake news by suggesting links to related Wikiped
ia articles. YouTube announced a similar plan in 2018.
>>> wikipedia.search("Falticeni")
['Falticeni', 'Foresta Falticeni', 'Charles, Prince of Wales', 'Sofia Ionescu',
'Buciumeni River (?omuzul Mare)', '?omuzul Mare River', 'Constantin Schumacher',
'Ionu? Atodiresei', '1967 Cupa României Final', 'J. J. Benjamin']
>>> wikipedia.page("Falticeni")
...
>>> city=wikipedia.page("Falticeni")
>>> city.title
...
>>> city.content
...
>>> wikipedia.set_lang("fr")
>>> page=wikipedia.page("Null")
>>> page.title
'Null' 
You can extract links:
>>> page = wikipedia.page("List_of_works_by_Leonardo_da_Vinci")
>>> print(page.links)
You can test all of these:
>>> dir(wikipedia)
['API_URL', 'BeautifulSoup', 'Decimal', 'DisambiguationError', 'HTTPTimeoutError
', 'ODD_ERROR_MESSAGE', 'PageError', 'RATE_LIMIT', 'RATE_LIMIT_LAST_CALL', 'RATE
_LIMIT_MIN_WAIT', 'RedirectError', 'USER_AGENT', 'WikipediaException', 'Wikipedi
aPage', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__na
me__', '__package__', '__path__', '__spec__', '__version__', 'cache', 'datetime'
, 'debug', 'donate', 'exceptions', 'geosearch', 'languages', 'page', 'random', '
re', 'requests', 'search', 'set_lang', 'set_rate_limiting', 'set_user_agent', 's
tdout_encode', 'suggest', 'summary', 'sys', 'time', 'timedelta', 'unicode_litera
ls', 'util', 'wikipedia']
Read more at pypi website.

Thursday, May 30, 2019

Python 3.7.3 : Using the win32com - part 007.

Today I show you a new script I tested a few days ago with win32com and Win32_LogonSession class, see thedocumentation.
The Win32_LogonSession WMI class describes the logon session or sessions associated with a user logged on to a computer system running Windows.
Let's see the script:
import win32com.client
from win32com.client import gencache
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Session")
for objItem in colItems:
    print("Caption" , objItem.Caption)
    print("Description" , objItem.Description)
    print("InstallDate" , objItem.InstallDate)
    print("Name" , objItem.Name)
    print("Status" , objItem.Status)
    print("StartTime" , objItem.StartTime)
    print("AuthenticationPackage" , objItem.AuthenticationPackage)
    print("LogonId" , objItem.LogonId)
    print("LogonType" , objItem.LogonType)
The result of this python script:
Caption None
Description None
InstallDate None
Name None
Status None
StartTime 20190530105325.022532+180
AuthenticationPackage LiveSSP
LogonId 8291403
LogonType 2
Caption None
Description None
InstallDate None
Name None
Status None
StartTime 20190530105325.022532+180
AuthenticationPackage LiveSSP
LogonId 8291220
LogonType 2
You can read info with this python module.
For example, the output tells me aboutLogonType.
You’ll see type 2 logons when a user attempts to log on at the local keyboard and screen whether with a domain account or a local account from the computer.

Python 3.7.3 : How fast are Data Classes.

This simple tutorial follows the PEP 0557 subject of Data Classes.
About the python classes then you can define into three ways:
  • standard_class;
  • slot_class ( standard_class with __slots__);
  • the new dataclass
Today I will show you how this works and how fast are these classes.
First, let's import some python modules: dataclasses and timeit.
The dataclasses python module lets us use the new dataclass.
This dataclass is a class decorator as defined in PEP 526.
For testing, I define a function to show us the output:
def  _str(n): return f'({n.x})'
This will get value and return it.
I define three classes for each type of these with one value named x and set to 1.0.
Each of these classes can have values and be used:
sc = standard_class(1.0)
sl = slot_class(1.0)
dc = new_dataclass(1.0)
This will set for each class the value 1.0 to x parameter.
The next step will start with the measure execution time of the time object creation for each of these classes.
Let's see the source code:
from dataclasses import dataclass
from timeit import timeit

def  _str(n): return f'({n.x})'

class standard_class:
 def __init__(self, x=0.0):
  self.x = x
 def __str__(self): return _str(self)

class slot_class:
 __slots__ = 'x'
 def __init__(self, x=0):
  self.x =x
 def __str__(self): return _str(self)

@dataclass
class new_dataclass:
 x: float = 0.0
 def __str__(self): return _str(self)

sc = standard_class(1.0)
sl = slot_class(1.0)
dc = new_dataclass(1.0)
print(sc,sl,dc)

time_sc=timeit('standard_class()', setup = 'from __main__ import standard_class')
print(f'standard class: {time_sc:.5f}')
time_sc=timeit('slot_class()', setup = 'from __main__ import slot_class')
print(f'standard class: {time_sc:.5f}')
time_sc=timeit('new_dataclass()', setup = 'from __main__ import new_dataclass')
print(f'standard class: {time_sc:.5f}')
The output is:
C:\Python373>python.exe dataclasses_001.py
(1.0) (1.0) (1.0)
standard class: 0.48912
standard class: 0.41349
standard class: 0.48514
As you can see, the new types of the class definition are not very fast but allow for other advantages and disadvantages.
You can read more about this at PEP 0557.


Monday, May 27, 2019

Python 3.7.3 : Using the win32com - part 006.

Today I will show you how to see the system environment setting:
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Environment")
for objItem in colItems:
    print("Caption:", objItem.Caption)
    print("Description:", objItem.Description)
    print("Install Date:", objItem.InstallDate)
    print("Name:", objItem.Name)
    print("Status:", objItem.Status)
    print("System Variable:", objItem.SystemVariable)
    print("User Name:", objItem.UserName)
    print("Variable Value:", objItem.VariableValue)
The result is :
...
Install Date: None
Name: PATH
Status: OK
System Variable: False...

Sunday, May 26, 2019

Python 3.7.3 : Using the win32com - part 005.

Another example with win32com python module:
This script show info about the audio or video codec, see this link:
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_CodecFile")
for objItem in colItems:
    print("Access Mask: " , objItem.AccessMask)
    print("Archive: " , objItem.Archive)
    print("Caption: " , objItem.Caption)
    print("Drive: " , objItem.Drive)
    print("Extension: " , objItem.Extension)
    print("File Name: " , objItem.FileName)
    print("File Size: " , objItem.FileSize)
    print("File Type: " , objItem.FileType)
    print("File System Name: " , objItem.FSName)
    print("Group: " , objItem.Group)
    print("Hidden: " , objItem.Hidden)
    print("Manufacturer: " , objItem.Manufacturer)
    print("Name: " , objItem.Name)
    print("Path: " , objItem.Path)
    print("Version: " , objItem.Version)
The output is this:
File Type:  Application Extension
File System Name:  NTFS
Group:  Video
Hidden:  False
Manufacturer:  Microsoft Corporation
Name:  C:\Windows\system32\MSVIDC32.DLL
Path:  \windows\system32\
Version:  6.3.9600.17415
Access Mask:  1179817
Archive:  True
Caption:  c:\windows\system32\l3codeca.acm
Drive:  c:
Extension:  acm
File Name:  l3codeca
File Size:  82432
File Type:  acm File
File System Name:  NTFS
Group:  Audio
Hidden:  False
Manufacturer:  Fraunhofer Institut Integrierte Schaltungen IIS
Name:  C:\Windows\system32\L3CODECA.ACM
Path:  \windows\system32\
Version:  1.9.0.401

Saturday, May 25, 2019

Python 3.7.3 : Using the win32com - part 004.

This is a source code I created a few days ago.
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ProgIDSpecification")
for objItem in colItems:
    print ("Caption: ", objItem.Caption)
    print ("Check ID: ", objItem.CheckID)
    print ("Check Mode: ", objItem.CheckMode)
    print ("Description: ", objItem.Description)
    print ("Name: ", objItem.Name)
    print ("Parent: ", objItem.Parent)
    print ("ProgID: ", objItem.ProgID)
    print ("Software Element ID: ", objItem.SoftwareElementID)
    print ("Software Element State: ", objItem.SoftwareElementState)
    print ("Target Operating System: ", objItem.TargetOperatingSystem)
    print ("Version: ", objItem.Version)
This script uses the win32com python module to show us info about Win32_ProgIDSpecification.
The result is strange and shows like this:
...
Version:  None
Caption:  Addin Class
...
See the full documentation at this link.

Friday, May 24, 2019

Python 3.7.3 : Using the win32com - part 003.

This is another python script with win32com python module and python version 3.7.3 .
The script shows us info about the drive:
import win32com
from win32com import client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
out_items = objSWbemServices.ExecQuery("SELECT * FROM Win32_DiskDrive")
for object_item in out_items:
    if object_item.Availability != None:
        print("Availability:" +  str(object_item.Availability))
    if object_item.BytesPerSector != None:
        print("BytesPerSector:" +  str(object_item.BytesPerSector))
    print("Capabilities:")
    strList = " "
    try :
        for obj_element in object_item.Capabilities :
            strList = strList + 'obj_element' + "," + obj_element
    except:
        strList = strList + 'null'
    print(strList)
    print("CapabilityDescriptions:")
    strList = " "
    try :
        for obj_element in object_item.CapabilityDescriptions :
            strList = strList + 'obj_element' + "," + obj_element
    except:
        strList = strList + 'null'
    print(strList)
    if object_item.Caption != None:
        print("Caption:" +  str(object_item.Caption))
    if object_item.CompressionMethod != None:
        print("CompressionMethod:" + str(object_item.CompressionMethod))
    if object_item.ConfigManagerErrorCode != None:
        print("ConfigManagerErrorCode:" + str(object_item.ConfigManagerErrorCode))
    if object_item.ConfigManagerUserConfig != None:
        print("ConfigManagerUserConfig:" + str(object_item.ConfigManagerUserConfig))
    if object_item.CreationClassName != None:
        print("CreationClassName:" + str(object_item.CreationClassName))
    if object_item.DefaultBlockSize != None:
        print("DefaultBlockSize:" + str(object_item.DefaultBlockSize))
    if object_item.Description != None:
        print("Description:" + str(object_item.Description))
    if object_item.DeviceID != None:
        print("DeviceID:" + str(object_item.DeviceID))
    if object_item.ErrorCleared != None:
        print("ErrorCleared:" + str(object_item.ErrorCleared))
    if object_item.ErrorDescription != None:
        print("ErrorDescription:" + str(object_item.ErrorDescription))
    if object_item.ErrorMethodology != None:
        print("ErrorMethodology:" + str(object_item.ErrorMethodology))
    if object_item.Index != None:
        print("Index:" + str(object_item.Index))
    #object_item.InstallDate - this is not show
    if object_item.InterfaceType != None:
        print("InterfaceType:" + str(object_item.InterfaceType))
    if object_item.LastErrorCode != None:
        print("LastErrorCode:" + str(object_item.LastErrorCode))
    if object_item.Manufacturer != None:
        print("Manufacturer:" + str(object_item.Manufacturer))
    if object_item.MaxBlockSize != None:
        print("MaxBlockSize:" + str(object_item.MaxBlockSize))
    if object_item.MaxMediaSize != None:
        print("MaxMediaSize:" + str(object_item.MaxMediaSize))
    if object_item.MediaLoaded != None:
        print("MediaLoaded:" + str(object_item.MediaLoaded))
    if object_item.MediaType != None:
        print("MediaType:" + str(object_item.MediaType))
    if object_item.MinBlockSize != None:
        print("MinBlockSize:" + str(object_item.MinBlockSize))
    if object_item.Model != None:
        print("Model:" + str(object_item.Model))
    if object_item.Name != None:
        print("Name:" + str(object_item.Name))
    if object_item.NeedsCleaning != None:
        print("NeedsCleaning:" + str(object_item.NeedsCleaning))
    if object_item.NumberOfMediaSupported != None:
        print("NumberOfMediaSupported:" + str(object_item.NumberOfMediaSupported))
    if object_item.Partitions != None:
        print("Partitions:" + str(object_item.Partitions))
    if object_item.PNPDeviceID != None:
        print("PNPDeviceID:" + str(object_item.PNPDeviceID))
    print("PowerManagementCapabilities:")
    strList = " "
    try :
        for obj_element in object_item.PowerManagementCapabilities :
            strList = strList + 'obj_element' + "," + obj_element
    except:
        strList = strList + 'null'
    print(strList)
    if object_item.PowerManagementSupported != None:
        print("PowerManagementSupported:" + str(object_item.PowerManagementSupported))
    if object_item.SCSIBus != None:
        print("SCSIBus:" + str(object_item.SCSIBus))
    if object_item.SCSILogicalUnit != None:
        print("SCSILogicalUnit:" + str(object_item.SCSILogicalUnit))
    if object_item.SCSIPort != None:
        print("SCSIPort:" + str(object_item.SCSIPort))
    if object_item.SCSITargetId != None:
        print("SCSITargetId:" + str(object_item.SCSITargetId))
    if object_item.SectorsPerTrack != None:
        print("SectorsPerTrack:" + str(object_item.SectorsPerTrack))
    if object_item.Signature != None:
        print("Signature:" + str(object_item.Signature))
    if object_item.Size != None:
        print("Size:" + str(object_item.Size))
    if object_item.Status != None:
        print("Status:" + str(object_item.Status))
    if object_item.StatusInfo != None:
        print("StatusInfo:" + str(object_item.StatusInfo))
    if object_item.SystemCreationClassName != None:
        print("SystemCreationClassName:" + str(object_item.SystemCreationClassName))
    if object_item.SystemName != None:
        print("SystemName:" + str(object_item.SystemName))
    if object_item.TotalCylinders != None:
        print("TotalCylinders:" + str(object_item.TotalCylinders))
    if object_item.TotalHeads != None:
        print("TotalHeads:" + str(object_item.TotalHeads))
    if object_item.TotalSectors != None:
        print("TotalSectors:" + str(object_item.TotalSectors))
    if object_item.TotalTracks != None:
        print("TotalTracks:" + str(object_item.TotalTracks))
    if object_item.TracksPerCylinder != None:
        print("TracksPerCylinder:" + str(object_item.TracksPerCylinder))
The result looks something like this:
MediaLoaded:True
...
MediaType:Fixed hard disk media
Model:TOSHIBA MQ01ABF050
Name:\\.\PHYSICALDRIVE0
Partitions:2
PNPDeviceID:SCSI\DISK&VEN_TOSHIBA&PROD_MQ01ABF050\4&AD866E5&0&000000
PowerManagementCapabilities:
 null
SCSIBus:0
SCSILogicalUnit:0
SCSIPort:0
SCSITargetId:0
SectorsPerTrack:63
Signature:-1846003871
Size:500105249280
Status:OK
SystemCreationClassName:Win32_ComputerSystem
SystemName:CATAFEST
TotalCylinders:60801
TotalHeads:255
TotalSectors:976768065
TotalTracks:15504255
TracksPerCylinder:255

Thursday, May 23, 2019

Python 3.7.3 : Using the win32com - part 002.

Today I tested the win32com python module with python 3.7.3.
I'll show you two scripts I tested with this python module.
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ClassicCOMClass")
for objItem in colItems:
    print("Component ID: " , objItem.ComponentId)
    print("Description: " , objItem.Description)
    print("Name: " , objItem.Name)
The result is something like this:
Name:  Shell Execute Hardware Event Handler
Component ID:  {FFC9F9AE-E87A-3252-8E25-B22423A40 }
Description:  System.ThreadStaticAttribute
Name:  System.ThreadStaticAttribute
Component ID:  {FFCDB781-D71C-4D10-BD5F-0492EAFFD }
Description:  PSFactoryBuffer
Name:  PSFactoryBuffer
Component ID:  {ffd90217-f7c2-4434-9ee1-6f1b530db }
Description:  XML Feed Moniker
Name:  XML Feed Moniker
Component ID:  {ffe1df5f-9f06-46d3-af27-f1fc10d63 }
Description:  HomeGroup CPL Advanced Settings Writer
Name:  HomeGroup CPL Advanced Settings Writer
Component ID:  {FFE2A43C-56B9-4bf5-9A79-CC6D42856 }
Description:  Windows Photo Viewer Image Verbs
Name:  Windows Photo Viewer Image Verbs
The following example contains this source code:
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ComponentCategory")
for objItem in colItems:
    print("Category ID: " , objItem.CategoryId)
    print("Name: " , objItem.Name)
The result is something like this:
Name:  3D DirectTransform
Category ID:  {F0B7A1A1-9847-11CF-8F20-00805F2CD }
Name:  Active Scripting Engine
Category ID:  {F0B7A1A2-9847-11CF-8F20-00805F2CD }
Name:  Active Scripting Engine with Parsing
Category ID:  {F0B7A1A3-9847-11CF-8F20-00805F2CD }
Name:  Active Scripting Engine with Encoding

Python 3.7.3 : Using the pelican python module and GitHub.

This tutorial follows a similar tutorial from the web.
I tested that tutorial to see if it works.
This tutorial is focused on GitHub but can also be used independently on another python platform.
You need a GitHub Pro, your personal account:
With GitHub Pro, your personal account gets unlimited public and private repositories with unlimited collaborators.

In addition to the features available with GitHub Free, private repositories on GitHub Pro include advanced tools and insights:

Unlimited collaborators
GitHub Pages
Wikis
Protected branches
Code owners
Repository insights graphs: Pulse, contributors, traffic, commits, code frequency, network, and forks

Let's start with pip install tool:
C:\Python373>cd Scripts

C:\Python373\Scripts>pip install pelican ghp-import
...
Installing collected packages: unidecode, blinker, feedgenerator, pelican, ghp-import
Successfully installed blinker-1.4 feedgenerator-1.9 ghp-import-0.5.5 pelican-4.0.1
 unidecode-1.0.23
Now you can create a new repository with your name into the GitHub website.
I create a repository named catafest:
C:\Python373\Scripts>git clone https://github.com/catafest/catafest.git blog
Cloning into 'blog'...
warning: You appear to have cloned an empty repository.

C:\Python373\Scripts>cd blog

C:\Python373\Scripts\blog>git checkout -b content
Switched to a new branch 'content'

C:\Python373\Scripts\blog>pelican-quickstart
Welcome to pelican-quickstart v4.0.1.

This script will help you create a new Pelican-based website.

Please answer the following questions so this script can generate the files
needed by Pelican.


> Where do you want to create your new web site? [.] .
> What will be the title of this web site? catafest
> Who will be the author of this web site? Catalin George Festila
> What will be the default language of this web site? [English]
> Do you want to specify a URL prefix? e.g., https://example.com   (Y/n) n
> Do you want to enable article pagination? (Y/n)
> How many articles per page do you want? [10]
> What is your time zone? [Europe/Paris] Europe/Bucharest
> Do you want to generate a tasks.py/Makefile to automate generation and publish
ing? (Y/n) y
> Do you want to upload your website using FTP? (y/N) n
> Do you want to upload your website using SSH? (y/N) n
> Do you want to upload your website using Dropbox? (y/N) n
> Do you want to upload your website using S3? (y/N) n
> Do you want to upload your website using Rackspace Cloud Files? (y/N) n
> Do you want to upload your website using GitHub Pages? (y/N) y
> Is this your personal page (username.github.io)? (y/N) y
Done. Your new project is available at C:\Python373\Scripts\blog
The content of the blog file:
[.]              [..]             [content]        Makefile
[output]         pelicanconf.py   publishconf.py   tasks.py
               4 File(s)          6,496 bytes
               4 Dir(s)  333,558,878,208 bytes free
The quickstart created five files and one new directory:

  • Makefile: make command convenience tasks for common operations such as running a development server, building a site and cleaning extraneous build files;
  • fabfile.py: A Fabric file that has some of the same types of commands as the Makefile. Fabric is a wonderful code library but for now I recommend skipping the Fabric file because unfortunately Fabric does not yet support Python 3;
  • develop_server.sh: shell script for running the development server;
  • pelicanconf.py: settings file for your Pelican project. If you are used to earlier versions of Pelican this file was instead named settings.py;
  • publishconf.py: another (optional) settings file that can be considered as a "production" settings file when you move past the development phase and want to deploy your site;
  • content: location for your markup files, which should be stored under pages and posts directories

Now we can use the local Git repo, commit the changes, and push the local changes to the remote repo hosted on GitHub:
C:\Python373\Scripts\blog>git add .
warning: LF will be replaced by CRLF in Makefile.
This can be fixed with:
git config core.autocrlf true
Check the first commit:
C:\Python373\Scripts\blog>git commit -m "first commit"

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'catal_000@catafest.(none)')
Add the mail and name to your git settings:
C:\Python373\Scripts\blog>git config --global user.email "catafest@yahoo.com"
C:\Python373\Scripts\blog>git config --global user.name "catafest"
Use the git for the first commit
C:\Python373\Scripts\blog>git commit -m "first commit"
[content (root-commit) 85814f7] first commit
 6 files changed, 230 insertions(+)
 create mode 100644 Makefile
 create mode 100644 README.md
 create mode 100644 git
 create mode 100644 pelicanconf.py
 create mode 100644 publishconf.py
 create mode 100644 tasks.py

C:\Python373\Scripts\blog>git push origin content
Enumerating objects: 8, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 2 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 2.91 KiB | 994.00 KiB/s, done.
Total 8 (delta 0), reused 0 (delta 0)
To https://github.com/catafest/catafest.git
 * [new branch]      content -> content
Create folders pages and images and create the first post with new file first-post.md.
C:\Python373\Scripts\blog>cd content
C:\Python373\Scripts\blog\content>mkdir pages images
C:\Python373\Scripts\blog\content>notepad first-post.md
Add content to the first post:
title: First Post on My Sweet New Blog
date: 
author: Your Name Here

#I am On My Way To Internet Fame and Fortune!

This is my first post on my new blog. While not super informative it
should convey my sense of excitement and eagerness to engage with you,
the reader!
Copy an image file into folder images.
I used the catafest.jpg image.
Create a new file into pages and named this file about.md.
C:\Python373\Scripts\blog\content>cd pages

C:\Python373\Scripts\blog\content\pages>notepad about.md
The content of about.md file is:
title: About
date: 

![So Schmexy][my_sweet_photo]

Hi, I am  and I wrote this epic collection of Interweb
wisdom. In days of yore, much of this would have been deemed sorcery
and I would probably have been burned at the stake.

😆

[my_sweet_photo]: {filename}/images/catafest.jpg
C:\Python373\Scripts\blog\content>cd pages

C:\Python373\Scripts\blog\content\pages>notepad about.md
Run Pelican to generate the static HTML files in the output:
C:\Python373\Scripts\blog\content\pages>notepad about.md

C:\Python373\Scripts\blog\content\pages>cd ..

C:\Python373\Scripts\blog\content>cd ..

C:\Python373\Scripts\blog>pelican content -o output -s publishconf.py
WARNING: Feeds generated without SITEURL set properly may not be valid
WARNING: Docutils has no localization for 'english'. Using 'en' instead.
WARNING: No valid files found in content for the active readers:
  | BaseReader (static)
  | HTMLReader (htm, html)
  | RstReader (rst)
Done: Processed 0 articles, 0 drafts, 0 pages, 0 hidden pages and 0 draft pages
in 0.23 seconds.

C:\Python373\Scripts\blog>ghp-import -m "Generate Pelican site" --no-jekyll -b m
aster output

C:\Python373\Scripts\blog>git push origin master
Enumerating objects: 49, done.
Counting objects: 100% (49/49), done.
Delta compression using up to 2 threads
Compressing objects: 100% (45/45), done.
Writing objects: 100% (49/49), 149.15 KiB | 2.98 MiB/s, done.
Total 49 (delta 5), reused 0 (delta 0)
remote: Resolving deltas: 100% (5/5), done.
remote:
remote: Create a pull request for 'master' on GitHub by visiting:
remote:      https://github.com/catafest/catafest/pull/new/master
remote:
To https://github.com/catafest/catafest.git
 * [new branch]      master -> master

C:\Python373\Scripts\blog>git add content

C:\Python373\Scripts\blog>git commit -m "added a first post, a photo and an abou
t page"
[content 4b036fd] added a first post, a photo and an about page
3 files changed, 21 insertions(+)
create mode 100644 content/first-post.md
create mode 100644 content/images/catafest.jpg
create mode 100644 content/pages/about.md

C:\Python373\Scripts\blog>git push origin content
Enumerating objects: 9, done.
Counting objects: 100% (9/9), done.
Delta compression using up to 2 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 20.28 KiB | 5.07 MiB/s, done.
Total 8 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/catafest/catafest.git
85814f7..4b036fd  content -> content
Open your browser and enter:
https://username.github.io
If you want to test it without Github, then use this:
C:\Python373\Scripts\blog>pelican -s pelicanconf.py -o output content
WARNING: Docutils has no localization for 'english'. Using 'en' instead.
WARNING: No valid files found in content for the active readers:
  | BaseReader (static)
  | HTMLReader (htm, html)
  | RstReader (rst)
Done: Processed 0 articles, 0 drafts, 0 pages, 0 hidden pages and 0 draft pages
in 0.19 seconds.

C:\Python373\Scripts\blog>cd output

C:\Python373\Scripts\blog\output>python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
Open your browser with the http://localhost:8000 URL.
You need to understand the difference between these two commands and how this make changes into output:
C:\Python373\Scripts\blog>pelican -s pelicanconf.py -o output content
WARNING: Docutils has no localization for 'english'. Using 'en' instead.
WARNING: No valid files found in content for the active readers:
  | BaseReader (static)
  | HTMLReader (htm, html)
  | RstReader (rst)
Done: Processed 0 articles, 0 drafts, 0 pages, 0 hidden pages and 0 draft pages
in 0.19 seconds.

C:\Python373\Scripts\blog>pelican content -o output -s publishconf.py
WARNING: Feeds generated without SITEURL set properly may not be valid
WARNING: Docutils has no localization for 'english'. Using 'en' instead.
WARNING: No valid files found in content for the active readers:
  | BaseReader (static)
  | HTMLReader (htm, html)
  | RstReader (rst)
Done: Processed 0 articles, 0 drafts, 0 pages, 0 hidden pages and 0 draft pages
in 0.23 seconds.
You can create themes and used into similar way like django with this command:
pelican -s pelicanconf.py -o output -t theme content
I do not want to extend this tutorial, but I can tell you that this python module is very versatile.