Labels

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday, 1 January 2013

Python Tricks

What is 'if __name__ == "__main__"' for?

Basically  __name__ is a built-in variable which help to self identify whether the program is running as standalone or it has been imported into some other programs. If it is run as standalone then __name__ variable would be assigned with value of __main__, otherwise not.

For example, create two files one.py and two.py as mentioned below. When you run the one.py from the command line, it prints 'aa' as the __name__ would have the value __main__. But it will be different when you run the two.py script which has imported the one.py:
one.py file has following code:
if __name__ == '__main__':

    print ('aa')
else:
    print ('bbb')

two.py has below code:
import one

Run the-- python two.py:
Output will be: 
>>> 
bbb

Run the-- python one.py:
>>> 
aa

How to implement arbitrary arguments in python? 
*args in a function declaration would help to accept and retrieve arbitrary number of arguments. For example:

create the following code and run it:

def argu(*args):
    #print(arg)
    print (args)
    for arg in args:
        print(arg)
    
argu(1,2,3,"test")

Output would be like this
(1,2,3,"test")
1
2
3
test

Similarly, **kwargs accepts arbitrary number of dictionary elements:
For example,

def argu(**kwargs):
    #print(arg)
    print (kwargs)
    for arg in kwargs:
        print(arg)
argu(one=1,two=2)   

And output would be something like this:
{'two': 2, 'one': 1}
two
one

And even if you don't pass any arguments (for example, call the function as argu()), the script still execute well.

Sunday, 16 December 2012

File download from Unix server using Python

We are going to see about File download from Unix or Linux server to your window machine using Python script.

There are 2 steps involved:
1> First establish the FTP connection
2> Download the files based on your needs


'''
filedownload.py
'''
# import required modulesa
from ftplib import FTP
import os

#Define the variables
ftpServer = 'yyy.com'  # or specify the IP address of the server
ftpUser = 'userx'
ftpPass = 'userpwd'
ftpFilePath = '/home/user/work/'
localDir = "C:\download"

# Function to connect FTP server
def ftpConnect():
    ftp = FTP(ftpServer)
    ftp.login(ftpUser,ftpPass)
    print ftp.sendcmd('pwd') # print the default home directory
    downloadFiles(ftp,ftpFilePath)
    ftp.quit()

# start downloading the files
downloadFiles(ftp,ftpFilePath):
    fileLists = []
   # create a local windows directory if does not exists 
    if not os.path.isdir(localFeedDir):
        os.mkdir(localDir)
   # Set the current working directory as the folder you want to download 
    ftp.cwd(path)
    ftp.retrlines('LIST',fileLists.append) #Lists out the files and directories 
    print "length is", len(fileLists) # prints the number of files in a directory

    for i in range(len(fileLists)): # extract only file name
        words = fileLists[i].split(None, 8)
        filename = words[-1].lstrip()
        local_filename = os.path.join(r"%s" %localDir, filename)
                lf = open(local_filename, "wb")
                ftp.retrbinary("RETR " + filename, lf.write, 8*1024)
                lf.close()

def main():
    ftpConnect()



Useful Links:

Python Doc