Results 1 to 8 of 8

Thread: Just Some Python Things Share/Save - My123World.Com!

  1. #1
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    Just Some Python Things

    Hello,

    This post is here so people can share their Python tips, tricks, hacks and best practices. This post follows the footsteps of bash cheat sheet here - http://garage4hackers.com/showthread.php?t=3100
    So, all the Pythonistas, share your tips, tricks and whatever you think is awesome about python.

    Regards,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  2. #2
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    Quick Web Server

    Hi,

    Want to share files between PCs? Want to test your html page? Need a quick simple http server? Call python.

    Here's the one liner that will start serving a web server on port 8000

    Code:
    batman@gothamcity ~ $ python -m SimpleHTTPServer
    Want to serve on a different port? Here's how

    Code:
    batman@gothamcity ~ $ python -m SimpleHTTPServer <port_number>
    Yup, that's all you need to do. Just open your browser and use it.
    Hope this will help you.
    Note: Tested on a Linux machine. Should work on Windows too.

    Regards,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  3. #3
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    Reversing a String

    In Python, you can reverse a string simply by using this syntax,

    Code:
    >>> string = "Garage4Hackers"
    >>> print string[::-1]
    srekcaH4egaraG
    The way this works is by using something known as "slicing". In above example above, we ask Python to print the string, using the negative step. This is explained in a better way here - http://stackoverflow.com/a/509295

    Fun Thing:

    Remember writing code to check if a string is a palindrome or not? Here's how to do, Python's way.
    Code:
    >>> string = "radar"
    >>> string == string[::-1]
    True
    Simple, right?

    Regards,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  4. #4
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    Handy Python Cheat Sheet

    Just came across a handy Python cheat sheet via @Punter. Posting this here so others could benefit from it and also so that I don't forget.

    Here it is - http://overapi.com/python/
    Enjoy.

    Regards,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  5. #5
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    File Handling Using "with" Statement

    In Python, if you want to read/write from a file, you might call "open()" first, and then read() or write() accordingly and then finally a close() to close that file handle.

    For example, one way to read from a local file is,

    Code:
    #!/usr/bin/env python
    
    f = open("/etc/passwd")
    print f.read()
    f.close()
    This code will simply output the content of file. However, downside with this code is if some error occurs between open and close call, the file handle might stay open and in some cases, the file might get corrupted too. A better way to handle files is using the "with" statement in Python. According to the official page https://www.python.org/dev/peps/pep-0343/, we see that

    This PEP adds a new statement "with" to the Python language to make
    it possible to factor out standard uses of try/finally statements.

    In this PEP, context managers provide __enter__() and __exit__()
    methods that are invoked on entry to and exit from the body of the
    with statement.
    What this means in simple words is, if you open a file using "with" and some error occurs, the __exit__() i.e. close() in this case will be called before the program goes out of this block.
    Another good definition/advantage is defined here http://preshing.com/20110920/the-pyt...nt-by-example/ -
    The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.
    The syntax for using "with" statement from official standard is,
    with EXPR as VAR:
    BLOCK

    Here, 'with' and 'as' are new keywords; EXPR is an arbitrary
    expression (but not an expression-list) and VAR is a single
    assignment target. It can *not* be a comma-separated sequence of
    variables, but it *can* be a *parenthesized* comma-separated
    sequence of variables.

    An example of reading and writing a file using "with" statement,

    Code:
    #!/usr/bin/env python
    
    with open("/etc/passwd", "r") as fin:
        content = fin.read()
        if "root" in content:
            print "root word found inside file"
    
    with open("/tmp/test.txt", "w") as fout:
        fout.write("I wrote this using 'with' in Python")
    I hope this helps.

    Cheers,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  6. #6
    Security Researcher
    Join Date
    May 2011
    Location
    Pune, Maharashtra, India
    Posts
    237
    Blog Entries
    1
    Couple of entries from my side

    Python simple server in version 3

    python -m http.server 8000
    Make python os independent.
    1. Avoid using os specific modules.
    1. use os.pathsep to seperate path's in path's


    Some helpful python modules that are life savers

    1. argparse : useful for taking commandline arguments from commandline.
    1. beautifulsoup : html parsing and processing module.



    Note: I will keep editing this same post to add more details in it.
    Website :
    To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

    Blog :
    To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

  7. #7
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1

    Parsing configuration files in Python

    There are various situations where instead of keeping configurations in the python script, we might need to keep an external config file. The advantage of keeping a config file is that then multiple scripts can access and use that conf file. The way Python provides this facility is via a library "ConfigParser". This library provides all the methods necessary to parse your config file.A great tutorial for the library can be found here - https://docs.python.org/2/library/configparser.html and here - https://pymotw.com/2/ConfigParser/. In this post, I'll show a basic usage case of ConfigParser.

    Example of config file (example.conf):

    Code:
    [global]
    path = /tmp/files/
    time = 90
    
    [app]
    restart = True
    The above config file contains two sections, global and app. We'll see how to parse this in following py scripts.

    Code:
    #!/usr/bin/env python
    
    import ConfigParser
    
    conf_parser = ConfigParser.ConfigParser() # Making a ConfigParser object
    conf_parser.read("example.conf") # The config file to parse
    
    path = conf_parser.get("global", "path") # Getting `path` setting from `global` section
    app_time = conf_parser.getint("global", "time") # Getting integer value
    restart = conf_parser.getboolean("app", "restart") # Getting boolean value
    
    print path, app_time, restart # Prints the config values
    That's it, pretty simple. For more detailed explanations and examples, please check out the mentioned resources. Hope this helps.

    Cheers,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  8. #8

    convert string to integer without using struct module

    A simple trick to save the script form loading "struct" module and converting string or binary data to number is as :

    num = int(data[:4][::-1].encode("hex"),16)

    and vice-versa would be :

    data = str(('%08X' % num).decode("hex")[::-1])

    ..."vinnu"

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •