JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Batteries included & Virtual Environments. os, Rich, Pint, glob.

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.

  1. Install a package: python -m pip install aPackage (Linux/macOS)/py -m pip install aPackage (Windows)
  2. Update a package: python -m pip install ‐‐upgrade aPackage (Linux/macOS)/py -m pip install ‐‐upgrade aPackage (Windows)
  3. Uninstall a package: python -m pip uninstall aPackage (Linux/macOS)/py -m pip uninstall aPackage (Windows)
  4. 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.

A) pip freeze outputs the installed packages and their versions in the current environment in the form of a configuration file: python -m pip freeze > requirements.txt.

B) Copy or move the requirements.txt to another environment and install all the packages with it: python3 -m pip install -r requirements.txt (Linux/macOS)/py -m pip install -r requirements.txt (Windows)

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 # 
from covid import Covid 
# https://pypi.org/project/covid/ is a 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: is 🇹🇭

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.

Python os

Python os

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 
>>> print(distance.to(ureg.miles)) # It converts from kilometers to miles.
6.21 mile
>>> time = 7.0 * ureg.minutes # time is a Quantity object 
>>> 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
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...
Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.