Batteries included & Virtual Environments

Síguenos / Follow us!
Facebooktwitterlinkedinrssyoutubeinstagram

Batteries included & Virtual Environments

Python has a “batteries included” philosophy. Python comes with a vast Standard Library right out of the box, making for a more efficient coding process. Furthermore, Python can be extended with third-party packages.

The Python Package Index (PyPI) is a repository of software for the Python programming language. PyPI helps you find and install software developed and shared by the Python community.

    • Make sure you have pip available: python3 -m pip --version (Linux/macOS)/py -m pip --version (Windows). If pip isn’t already installed, then try: python3 -m ensurepip --default-pip (Linux/macOS)/py -m ensurepip --default-pip (Windows)
    • Install a package: python -m pip install aPackage (Linux/macOS)/py -m pip install aPackage (Windows)
    • Update a package: python -m pip install --upgrade aPackage (Linux/macOS)/py -m pip install --upgrade aPackage (Windows)
    • Uninstall a package: python -m pip uninstall aPackage (Linux/macOS)/py -m pip uninstall aPackage (Windows)
    • Searching for packages: python -m pip search "aPackage" (Linux/macOS)/py -m pip search "aPackage" (Windows)

Python “Virtual Environments” allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally. They prevent packaging conflicts between multiple Python projects.

Let's put it into practice.

import os

This module provides a portable way of using operating system dependent functionality. It provides functions for interacting with the operating system.
>>> import os
>>> print("Current working directory:", os.getcwd())
Current working directory: /home/myUser
>>> dir_list = os.listdir(os.getcwd())
>>> print("Files and directory in current working directory ", dir_list)
Files and directory in current working directory ['Dropbox', '.bash_history',...]

from rich import print # Rich is a Python library for rich text and beautiful formatting in the terminal.
from covid import Covid # Python package to get information regarding the novel corona virus provided by Johns Hopkins university and worldometers.info, pip install covid.
from time import gmtime, strftime, sleep # This module provides various time-related functions

os.system("/usr/games/fortune -s | /usr/games/cowsay | /usr/games/lolcat") # os.system(command) method execute the command (a string) in a subshell. fortune is a command-line utility that displays a random quotation from a collection of quotes. When fortune is piped to cowsay, it generates an ASCII picture of a cow which displays the random quotation. lolcat adds rainbow coloring to it. However, this is operating system dependent. 

orden = "ncal -b" # It displays a calendar on the terminal. 
print(strftime("Date: %d(%A)-%m-%Y. Time: %H:%M:%S", gmtime())) # Convert a tuple or struct_time representing a time as returned by gmtime() to a string as specified by the format argument. %d(%A)-%m-%Y: Day of the month(full weekday name)-Month as a decimal number-Year with century. 
os.system(orden)

print("[orange]Date and Time in Bangkok, Thailand[orange] ", ":thailand:") # Rich supports a simple markup which you can use to insert color and styles virtually everywhere. If you write a style in square brackets, e.g. [orange], that style will apply until it is closed with a corresponding [/orange]. If you add an emoji code, it will be replaced with the equivalent Unicode character. An emoji code consists of the name of the emoji surrounded by colons (:), e.g., :thailand:

os.system("TZ=Asia/Bangkok date")
covid = Covid(source="worldometers") # It gets data from Worldometer.info
print("COVID. Total Active Cases", covid.get_total_active_cases(), "Total Deaths", covid.get_total_deaths()) # Get total deaths
print("Spain. Confirmed Cases:", covid.get_status_by_country_name("spain")['confirmed'], "New Cases:", covid.get_status_by_country_name("spain")['new_cases'], "Deaths:", covid.get_status_by_country_name("spain")['deaths'])
os.system('curl \'wttr.in/{Málaga, Bangkong}?format=3\'')

cURL is a command-line tool for getting or sending data including files using URL syntax. The most basic command in curl is curl http://website.com. wttr.in is a console-oriented weather forecast service. It helps us to check the time of any location, e.g., Málaga and Bangkong.

learn Python
Pint is a Python package to define, operate, and manipulate physical quantities. It allows arithmetic operations between them and conversions from and to different units.

To install Pint, simply: python3 -m pip install pint.

user@pc:~$ python
Python 3.9.5 (default, May 11 2021, 08:20:37) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pint import UnitRegistry
>>> ureg = UnitRegistry() # It initializes a UnitRegistry() object. It stores the unit definitions, their relationships, and handles conversions between units.
>>> ureg.default_format = '.2f' # It defines the default formatting string, it rounds the result to two decimal places.
>>> temperature = ureg.Quantity(29, ureg.degC) # It defines a Quantity object (it describes a physical quantity) with a value (29) and the units of the physical quantity (Celsius).
>>> print(temperature.to('degF')) # It convert from Celsius to Fahrenheit.
84.20 degree_Fahrenheit
>>> distance = 10 * ureg.kilometer # distance is a Quantity object <Quantity(10, 'kilometer')>
>>> print(distance.to(ureg.miles)) # It converts from kilometers to miles.
6.21 mile
>>> time = 7.0 * ureg.minutes # time is a Quantity object <Quantity(7.0, 'minute')>
>>> print(time.to(ureg.second)) # It converts from minutes to seconds.
420.00 second
>>> speed = ureg.Quantity(45, 'm/seconds')
>>> print(speed.to('in/hour'))
6377952.76 inch / hour

The glob module is used to retrieve files/pathnames matching a specified pattern. We are going to use it to find files recursively and then search for specific words in those files.

import glob, os
def searchFileLine(wordSearched, fileSearched):
    with open(fileSearched) as f:

To open the file, use the built-in open() function. It returns a file object (f). The with statement will automatically close the file after the nested block of code is executed.

        lines = f.readlines() # The readlines() method returns a list containing each line in the file as a list item. 

        for line in lines:
            if wordSearched in line: # If we find the word in the file
                print(fileSearched)
                print(line)

def searchPeople(namePerson, myPath):
    print("Searching... " + namePerson)
    os.chdir(myPath) # It changes the current working directory to the given path.
    files = glob.glob("**/*.md", recursive=True) # If recursive is True, the pattern ** will match any files, directories, and subdirectories.
    for file in files: # It iterates over all retrieved files
    	searchFileLine(namePerson, myPath + "/" + file)

if __name__ == '__main__':
    searchPeople("Carmen", "/home/myUser/Dropbox")

Aunty M Carmen: 956.... Residencia de la Torre...
Compártelo / Share it!
Facebooktwitterredditpinterestlinkedinmail

Author: Anawim

I am a social activist. I have two Bachelor's degrees, Maths and Computer & Software Engineering. I also have a Ph.D. in Psychology. I have written nine published books, four scientific articles, and five scientific presentations. I simply want to contribute to making a difference where it counts, so that we make the world a better, more sustainable, prosperous, and fairer place. I am always willing to give free talks and lectures about the social problems that exist in our world today.

Leave a Reply

Your email address will not be published. Required fields are marked *