Category Archives: Python

Execute a subprocess with timeout in Python

In Python 2.6+, normally we use a subprocess to execute a command line. To add timeout capability, we can take advantage of threading where we run the command in a thread and kill the thread if timeout. Below is an … Continue reading

Posted in Python | Leave a comment

Submit REST request in Python

The code snippet below illustrates how to submit REST requests in Python.

Posted in Default, Python | Leave a comment

How to ping a host in Python

One could write a small function in Python to ping a host. Below is the code snippet.

Posted in Python | 1 Comment

Python Regex Examples

This post illustrates a list of examples of what you can do using regex in python. Strip out the leading http(s) prefix. hostname = re.sub(r’https?://’, “”, hostname.lower()) Match a string with regex: if re.match(regex, value, flags=re.IGNORECASE) is None: print(“Fail to … Continue reading

Posted in Python | Leave a comment

Walk a Directory Tree in Python

This example demonstrate how to walk a directory tree and replace pattern blob in Python. Unwanted directories and files are excluded. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, … Continue reading

Posted in Python | Leave a comment

How to catch all exception in Python?

If you look at the Python exception hierarchy at https://docs.python.org/3/library/exceptions.html#exception-hierarchy, we can see that all the exceptions and erorrs are derived from BaseException. Thus the code below would catch all the exception: #!/usr/bin/python try: raise SystemExit(“this is a system exit”); … Continue reading

Posted in Default, Python | Leave a comment

Lex and Yacc example in Python

PLY is a parser implemented using Lex and Yacc. It can be downloaded from here: http://www.dabeaz.com/ply/ Note: – Lex (a lexer) does lexical analysis, which separating a stream of characters into different words (tokens). Lexer works at the word level. … Continue reading

Posted in Compiler, Python | Leave a comment

Dedupe a list without changing item order in Python

In Python, if one wants to remove duplicates items in a given list. The simplest approach would be feed the list in to a set function, and only the unique elements will remain in the output result. However, the side … Continue reading

Posted in Python | Leave a comment

Python string processing

Remove trailing newline: Split string at delimiter: 1. Regular expression: 2. Traditional:

Posted in Python | Leave a comment

File IO in Python

File IO: Approach 1: Approach 2: Path join: Output: >>> path1/path2 Create directory if not exist:

Posted in Python | Leave a comment