Python – What are Context Managers?

What are Context Managers? Context managers are constructs that allow you to set something up and tear something down automatically, by using using the statement – with.  For example you may want to open a file, write to the file, and then close the file. Here is an example of a context manager, with open(path, … Read more

Python – What are Abstract Classes?

An abstract class can be considered a blueprint for other classes, allowing you to mandate a set of methods that must be created within any child classes built from your abstract class. Creation Lets first look at how you create an abstract class. First we import abc, we define the class as a metaclass using … Read more

Connecting to a SOCKS Proxy within Python

The SocksiPy python module provides a simple way to connect via a SOCKS proxy. Within this article we will show you 2 examples on how to use SocksiPy. General Below allows you to establish a connection via a SOCKS proxy[1]. import socks socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, “127.0.0.1”, 8080) socket.socket = socks.socksocket import urllib2 print urllib2.urlopen(‘http://www.google.com’).read() URLLIB2 Only Should … Read more

Python – Packing and Unpacking Dictionaries

Today I will explain the concept of unpacking and packing within Python. Unpacking Unpacking allows us to pass keyword arguments (i.e dictionary) to a function via the use of the ** syntax. We can then access the values within the function like so, >>> def do_something(**kwargs): … print kwargs[‘a’] … print kwargs[‘b’] … print kwargs[‘c’] … Read more

Python – What is TDD (Test-Driven Development) ?

What is TDD ? TDD (Test-driven development) is software design approach where your code is written around your tests. With TDD the test is first created, this test initially fails. The minimum amount of code is then written to ensure the test passes. This approach provides the following benefits, promotes the creation of more efficient … Read more

Python – No module named MySQLdb

Issue When trying to import MySQLdb you may find that the module is not available. And experience an error such as, django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb Solution The solution is to install MySQL-python i.e pip-2.7 install MySQL-python PIP INSTALL Error However, when trying to install MySQL-python you may then get the following … Read more

Python – Show differences between 2 Lists

Below shows you how to compare and show the differences between 2 lists by using the set command, >>> set([1563, 1564, 1565, 1566, 1567]).symmetric_difference([1563, 1564, 1565, 1566, 157]) set([1567, 157])

Python – Split a String into a Dictionary

To split a string into key value pairs (i.e dict) the following can be used, >>> string = “abc=123,xyz=456” >>> dict(x.split(‘=’) for x in string.split(‘,’)) {‘xyz’: ‘456’, ‘abc’: ‘123’}

Python – Check for Items across Sets

Within this example we will check if the same item exists across 2 sets. If so then a boolean is returned, >>> s1 = set([1, 2, 3])>>> s2 = set([3, 4, 5])>>> bool(set(s1) & set(s2))True

How to Print the File Location of a Python Module

The are times were you may need to print the location of a python module. There are a number of ways to achieve this. However the most simplistic method  have found is to use ‘inspect’. Below shows you an a example, >>> import inspect>>> import urllib2>>>>>> print inspect.getfile(urllib2)/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.pyc

Python – Create a Dictonary using List Items as Keys

Below shows you how to create a dictionary using keys from list items using list comprehension. From this we can also set a default value. >>> keys = [‘a’,’b’,’c’,’d’]>>> { x:False for x in keys }{‘a’: False, ‘c’: False, ‘b’: False, ‘d’: False}

How to Build a TCP Connection in Scapy

Scapy is a packet manipulation program written in Python by Philippe Biondi. Within this article I will show you the code required to build a 3WHS within Python using Scapy. Prevent RST At the point you send the SYN from Scapy and the SYN-ACK is returned. Because the Linux kernel receives the SYN-ACK but didn’t … Read more

Python – How do I merge 2 dictionaries ?

Below shows you how to merge 2 dictionaries. It is also worth noting that any items will be overwritten by the 2nd dictionary should they exist in both. This is also shown below via the bananas items. >>> x = {‘apples’: 1, ‘bananas’: 2}>>> y = {‘bananas’:3 , ‘coconuts’: 4}>>> dict(x.items() + y.items()){‘coconuts’: 4, ‘apples’: … Read more

Python – Filtering a dictionary against a list of values

This short Python snippet shows you how to filter a dictionary against a list of values via the use of a list comprehension. >>> d = {“apples”:1,”bananas”:2,”pears”:3} >>> {x:y for x,y in d.iteritems() if x in [“apples”,”pears”]}{‘apples’: 1, ‘pears’: 3}

Python 2.7.5 : ImportError: No module named _sqlite3

After compiling Python 2.7.5 you may find yourself being unable to to import sqlite3 and receiving the following error message, ImportError: No module named _sqlite3 Solution Install sqlite-devel via ‘yum install sqlite-devel’ Recompile Python. Note : Details on how to compile Python can be found within the following article.    

How to install easy_install-2.7 and pip-2.7

Within this quick tutorial we will show you the steps required to install easy_install-2.7 and pip-2.7. Install  wget –no-check-certificate tar xf distribute-0.6.35.tar.gzcd distribute-0.6.35python2.7 setup.py install easy_install-2.7 pip Confirm [root@server]# easy_install-2.7error: No urls, filenames, or requirements specified (see –help) [root@server]# pip-2.7 -Vpip 1.3.1 from /usr/local/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg (python 2.7)

How do I compile mod_wgsi for Python 2.7

Recently I found myself in a situation where I needed to recompile mod_wgsi against a newer version of Python. This involves recompiling Python with the correct flags, then recompiling mod_wsgi using the newly compiled Python. Below shows the steps, Check Version First of all check what version of Python mod_wsgi was compiled with. [root@server]# ldd … Read more

Create a Multiline Cell Based CSV File Within Python

Within this short tutorial we will show you the steps required to create a csv file that includes multi-line cells within Python. In order to create a mutliline cell within Excel (2010/2013) the following is required: newlines are represented with a carriage return/newline, the string should be wrapped in quotes. One of the great things … Read more

Python – List Comprehensions

List comprehensions provide an more Pythonic and alternative way (i.e instead of using map and filter) in which to express a list. There are 3 components to a list comprehension. The expression, the for loop and the optional condition. As you can see below, by changing the expressions and enclosing brackets to your expression you … Read more

Python – What does ‘if __name__ == “__main__”‘ mean ?

Within a Python program you may see the following syntax, if __name__ == “__main__”:    …(your code)… What does this mean ? When a Python program is run directly it runs within the __main__ namespace. However when a python script is imported as a module it runs within its own namespace. This statement checks the namespace … Read more

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial