Thursday, June 14, 2018

Difference of Single Aterisk * to Double Asterisk ** in python argument


The single asterisk in argument is given to read multiple arguments at once . In the below code if we call multiply(3,4,5,6) then the code will read all the inputs and then multiply. Otherwise we can not read multiple arguments.

def multiply(*args):
    total=1
    for arg in args:
        total*=arg
    return total

>>> multiply(3,4,5)
....  60
====================== 
If we want to read a dictionary as argument or arbitrary keyword arguments then ** is needed.e.g.

def accept(**kwargs):
    for keyword, value in kwargs.items():
        print("%s -> %r" % (keyword, value))

>>> accept(foo=2,faa=3,gaa="gaa")
('foo', 2)
('faa', 3)
('gaa', 'gaa')
>>> 

====================== 

Sunday, April 22, 2018

Reportlab Module

Hey guys, I have found a cool module to print anything to pdf format. The name of the module is reportlab. If you have pip installed in your system then simply write the following in command prompt.

>>> pip install reportlab

The reportlab will automatically be detected anddownloaded if you have a proper internet connection.
Below is a simple code to run and print pdf file form python -

from reportlab.pdfgen import *
def hello(c):
    c.drawString(100,100,"Hello World")
c=canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()

The code will create a file hello.pdf with "Hello World" written on it. If you want to learn more about reportlab below is the link to learn more - 

Sunday, October 22, 2017

How to Create Your Own Module

The simplest way to create your own module is by using function in Python. Python provide a cest way to create your own module. For example suppose you have function like below -

def myModule(wannasay):
'''This module will say whatever you wanna say'''
return "I wanna say"+str(wannasay)
def calculate(x,y): '''This will add two numbers''' return x+y

    
Save the above code by naming it myModule.py and save it in same directory where you want to create a file which will call it.This is the way we have created the module with methods MyModule and calculate. In the program where we need the module we have to do only one thing is just to import it by the 'import' statement. Lets see how it is done -

import myModule

print "I wanna say something"
myModule.myModule("I am a bad ass lier")

print "Now I wanna calculate"
myModule.calculate(4,6) 


Up, we have imported the file. We put the module file in the same location as the file which called it. We can also put the module in the path of python, where the calling file will automatically search.  Now we used the functions in the module the same way we generally use function in python.

You can find the files here to test yourself -
https://drive.google.com/file/d/0Bx4xTppgmBd-N2wtY2ktVUItQm8/view?usp=sharing
https://drive.google.com/file/d/0Bx4xTppgmBd-SWQ3Uk9GWUZPRUU/view?usp=sharing


Monday, October 16, 2017

How to use python to create Union as in C


The below example shows how to use python to create a union and use it.
from ctypes import *
class barley_amount(Union):
   _fields_ = [
   ("barley_long", c_long),
   ("barley_int", c_int),
   ("barley_char", c_char * 8),
 ]
value = raw_input("Enter the amount of barley to put into the beer vat:")
my_barley = barley_amount(int(value))
print "Barley amount as a long: %ld" % my_barley.barley_long
print "Barley amount as an int: %d" % my_barley.barley_long
print "Barley amount as a char: %s" % my_barley.barley_char
  


(ref: gray hat python) 

Sunday, September 24, 2017

How to Use C Programming Language with Python



C is one of the first programming language a programmer should learn. But the syntax of the language and semicolons make it hard. But C is the most powerful language ever created. So, we want to use power of C in python and python provides a very good way to do so.

On windows the C runtime is msvcrt.dll which is located in C:\Windows\System32 and on linux it is libc.so.6. We will write a code in Windows and see the result. So Let us C -


from ctypes import *
msvcrt=cdll.msvcrt
message_string="My Name is Anthony\n"
msvcrt.printf("Testing %s",message_string)

In the above code we import all the modules of ctypes, which is responsible for using C in python. Then assign a variable to the dll we need to run the code in the second line. Next, the string we want to print. In the next statement we use pure C function printf() to print our message.

Similarly for Linux OS we need to do a little change. Just replace the second statement to have that libc.so.6. e.g.


from ctypes import *
libc = CDLL("libc.so.6")
message_string="My Name is Anthony\n"
msvcrt.printf("Testing %s",message_string)

That's all for today. In the next entry we'll learn about structure and Union.

(ref: Gray Hat Python)

Thursday, August 31, 2017

Extracting Email id Using Python Regular Expression



Regular expression is handy for extracting important part from a document or a string.  Suppose you want to extract email id from a string then it can be easily done by '\S+@\S+' this expression. Where \S represents non-whitespace character, then followed by an @ sign and again by \S;as actually it is in a generic email id. So , let's get the code and extract email id - 


import re

str = 'I have tried to email you at medhrk@gmail.com but it did not work so I send the mail to you by using your rediff account idhrk@rediffmail.com  at  @2PM'

lst = re.findall('\S+@\S+', str)

print lst  


The output will be  - ['medhrk@gmail.com',√≠dhrk@rediffmail.com],  

Wednesday, July 5, 2017

Copying with Pyperclip


Pyperclip is a python module for copying and pasting clipboard content. pyperclip.copy() and pyperclip.paste() functions are the main functions of the modules and works in the same manner as the name implied. Peruse the below code and try to grasp what the code will do -

import pyperclip

while True:
    fh=open('allcopies1.txt','a+')    
    text=str(pyperclip.paste())
    if text not in str(fh.read()):
        fh.write(text)
        fh.write("\n\r\n")
    else:
        print "Already Copied"
        fh.close()
        break
fh=open('allcopies1.txt','r')
for word in fh:
    print word
       

This program is useful when you need to have a file for storing all the copied content. Make sure the file has a 777 permission. After opening the file we check if the content of the clipboard copied previously? If not then it adds the clipboard content to the file.
A small but useful tool for big future programs. Can you name me instances when it can be used.

ref: Automate boring stuff by python.

Difference of Single Aterisk * to Double Asterisk ** in python argument

The single asterisk in argument is given to read multiple arguments at once . In the below code if we call multiply(3,4,5,6) then the code...