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
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
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
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
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
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
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])
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’}
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
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
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}
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
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
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}
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.
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. [[email protected]]# ldd … Read more
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 [[email protected]]# easy_install-2.7error: No urls, filenames, or requirements specified (see –help) [[email protected]]# 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)
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
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
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
A decorator provides a simplified way to pass one callable object to another (i.e a class or function). The main benefit of decorators is that it allows you to clearly state where and what objects are being passed to each other. Typically this can be achieved by the following. Without Decorators As you can see, … Read more
Within this article we will show you how to import a python module that is located within a different folder. This example will be based upon your folder structure including a folder named ‘module’ and the path ‘/opt/django/myproject/’ already being within your python system path. Example Folder Structure Below shows you a quick example of … Read more
Below is a python function that I created. The purpose of this function is to print correctly aligned columns using variable length items. The result is that you can pass the function a list (or list of lists), the same list is returned with each item padded to the maximum item length within the relating … Read more
To print the path of python module the command print [module].__file__. An example is shown below: [[email protected] ~]# pythonPython 2.4.3 (#1, Sep 21 2011, 19:55:41)[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2Type “help”, “copyright”, “credits” or “license” for more information.>>> import pexpect>>> print pexpect.__file__/usr/lib/python2.4/site-packages/pexpect.pyc
Below is a small script to convert temperatures between celcuis and fahrenheit (and vice versa). This article / script is meant as reference point rather than a full tutorial. #!/usr/bin/python import sys def convert(t,fc): if t == “2f”: print (fc * 9) / 5 + 32,”Degress Fahrenheit” elif t == “2c”: print (fc – 32) … Read more
Below is a short script designed to output the addressable IP addresses within a given subnet. Note : This script requires the netaddr python library. #!/usr/bin/pythonimport sysfrom netaddr import IPNetworkIPADDRESS = raw_input(‘Enter Subnet:’)try: for ip in IPNetwork(IPADDRESS).iter_hosts(): print ‘%s’ % ipexcept: print “Usage: “,sys.argv[0],”[SUBNET ID]/[NETMASK]” print “Output addressable ip addresses within a given subnet.” … Read more
Below is a small example to show some of the various way in which print can be called within Python. quote = “A person who never made a mistake never tried anything new.”print(“ORIGINAL”)print(quote)print(“\nUPPERCASE”)print(quote.upper())print(“\nLOWERCASE”)print(quote.lower())print(“\nTITLE”)print(quote.title())print(“\nREPLACE”)print(quote.replace(“person”, “banana”)) Output [[email protected]]# python print_example.py ORIGINALA person who never made a mistake never tried anything new.UPPERCASEA PERSON WHO NEVER MADE A MISTAKE … Read more
This python script will connect to a designated FTP server. Obtain a list of all files, then sort all files with a .jpa extension and then download the latest one. In order to do this regular expressions are used to build a list of files only containing .jpa file extensions. This list is then sorted … 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