Tag: programming

In PyTips I'll be talking about Python features, standard libraries, and interesting packages found on PyPi. The idea is to have a short write up and accompanying code snippets for all Python things that I found useful and interesting. These will be mostly aimed at beginners, and I hope that you too, my reader, will find them helpful. Problem A common idiom while looping over collection is to use helper variable to store index of the element currently worked on. For example, we want to convert IP address from dotted-decimal to the decimal format: my_ip = '10.16.32.113'...

Continue reading »

Have you ever found yourself needing to quickly sort IP addresses directly from the Linux shell? You just ran grep against all of your configs looking for IPs in some subnet, but they're all unordered, and you just wish you could pipe the output and have them sorted. I kept running into the same problem. When it got painful enough I found a website that allowed me to copy-paste and sort all of the IPs. That worked for a while but wasn't satisfying enough. Then I found a cool looking bash one-liner, with cut, sort, and other unix utilities, combined...

Continue reading »

Often we need to read from, or write to, files in directories that are local to our script. For instance, we could use the below code to save to file all possible values that can be stored in one byte: my_bytes = bytearray(list(range(0,256))) with open("output/local.bin", 'wb') as f: f.write(my_bytes) Our script, local_file.py, is located in the following directory: /home/python [wintermute@hive python]$ cd /home/python [wintermute@hive python]$ ls local_file.py output Now, let's say we launch this script from within its location: [wintermute@hive python]...

Continue reading »

Have you ever had a need to iterate over two lists at the same time? I did recently and it turns out that Python has a built-in function called zip() that can be used for this. This function takes iterables as arguments, such as lists or strings, and returns a list of tuples containing elements from each of the arguments. When using it in our code we can mix types of arguments, they don't have to be the same. In the examples below we will use lists of characters, digits, and tuples. For good measure, we will throw in a...

Continue reading »

I recently had a need to read values from a file and insert them into a dictionary of dictionaries. This could be useful for having, say, dictionary with hostnames of some devices as keys and values being dictionaries with data collected from each of the devices. To achieve that I created a helper dictionary which had data for each device that I read from a file. Then I would assign a copy of a helper dictionary to the key equal to the name of the device for which I collected data. My code was functionally identical to the below snippet:...

Continue reading »