Is production: true

Python

Python, created by Guido van Rossum and first released in 1991, is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with its notable use of significant indentation.

The language draws developer’s eye sight due to

Python continues to be one of the most popular programming languages in the world, with a growing community and a constant stream of new libraries and frameworks.

Web Site

Tools

Basic


Use of future For Type Hint in python, before 3.10+, the coding is not easy to understand, especialy when using the syntax "SomeType".

Using from __future__ import annotations

In Python 3.7–3.9, you can enable postponed evaluation of type annotations by importing annotations from the __future__ module. This means all type hints are stored as strings and only evaluated when needed, allowing you to:

This feature is enabled by default in Python 3.10, but was reverted in 3.11+ (see PEP 563 and PEP 649 for details). In 3.7–3.9, you must import it explicitly.

Example: Forward Reference in Type Hints

from __future__ import annotations

class Node:
    def __init__(self, value: int, next: Node | None = None):
        self.value = value
        self.next = next

    def set_next(self, next_node: Node) -> Node:
        self.next = next_node
        return self

head = Node(1)
second = Node(2)
head.set_next(second)

Notes:


group n items in a list to sub list


s="""
10.0.0.1
user1
password1
10.0.0.2
user2
password2
"""
s=[ss for ss in s.split('\n') if ss!='']

def pad_every_n_lines(n: int, data: [str])->[[str]]:
    import json
    output = {}
    for index, item in enumerate(s):
        row = index // n
        item_value = index % n
        if str(row) not in output:
            output[str(row)] = {}
        output[str(row)][str(item_value)]=item
    final_output=[]
    for key1 in output:
        arr = []
        for key2 in output[key1]:
            arr.append(output[key1][key2])
        final_output.append(arr)
    return final_output
            
    
[e for e in pad_every_n_lines(3, s)]

# [['10.0.0.1', 'user1', 'password1'], ['10.0.0.2', 'user2', 'password2']]

pad array into dictionary


def pad_arr_as_dict(header: [str],data: [str])->dict[str,str]:
    item ={}
    for index, key in enumerate(header):
        item[key]=data[index]
    return item



pad_arr_as_dict(["ip","un", "pwd"], [ "10.0.0.1", "user1", "password1"])

# {'ip': '10.0.0.1', 'un': 'user1', 'pwd': 'password1'}

Generate string of markdown table

def gen_md_table(header: [str], data: [dict[str,str]]):
    header_line = " | ".join(header)
    header_line = f"|{header_line}|\n"
    second_line = " | ".join(map(lambda x: "---", header))
    second_line = f"|{second_line}|\n"
    data_rows = "\n".join(map(lambda x: f"|{x}|",map(lambda x: " | ".join(map(lambda y: x[y], header)), data)))
    return header_line+second_line+data_rows

gen_md_table(["ip","un", "pwd"], [
    {"ip":"10.0.0.1","un":"user1","pwd":"password1"},
    {"ip":"10.0.0.2","un":"user2","pwd":"password2"}
])

# |ip | un | pwd|
# |--- | --- | ---|
# |10.0.0.1 | user1 | password1|
# |10.0.0.2 | user2 | password2|

Use python to decode json from stdin

# pipe in the json data
# then extract as dict in python

# echo '{"a": {"b": 123}}' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['a']['b'])"

# expected resule
# output: 123

A command line tools called jq is also workable, but require extra installation for the tool.


Read/Write data from clipboard

In python read / write data from clipboard, pyperclip is required.

import pyperclip
data = clipboard_data = pyperclip.paste()

Extract XML data

In python extracting xml data, requires package lxml.

from lxml import etree
xml_str="?"
dom = etree.fromstring(xml_str.encode('utf-8'))
len(dom.xpath('//some-tags'))

Read XML from clipboard and load into lxml for processing

import pyperclip
from lxml import etree
xml_str = clipboard_data = pyperclip.paste()
dom = etree.fromstring(xml_str.encode('utf-8'))
dom.xpath('//{tag}')

Related articles:

Python Script to Search Kill Process
March 11, 2025 by Xeth [~1 mins]

A simple snippet to find process by name and kill the process

#windows
#python