Python Collection 20150301
This is a next version of Python Collection 20150209 - Shammerism.
Adding argparse examples.
If-else
if x > 0: print "X is bigger than 0." else: print "X is less than 0."
If-elif-else
if x > 0: print "X is bigger than 0." elif x == 0: print "X is zero." else: print "X is less than 0."
File read and output(like cat which is major unix command line tool)
f = open('test-text.txt') data = f.read() f.close() lines = data.split('\n') for line in lines: if 0 < line.find(target) : print line
Send HTTP GET Requests
connection = httplib.HTTPSConnection(host) connection.request("GET", uri) response = json.loads(connection.getresponse().read()) print response
Send HTTP POST Requests
requestHeader = {"Content-type": "application/x-www-form-urlencoded"} connection = httplib.HTTPSConnection(host) connection.request("POST", uri, parameters, requestHeader) response = json.loads(connection.getresponse().read()) print response
If post data is json format, Content-type should be below.
requestHeader = {"Content-type":"application/json"}
Parsing command line arguments
import argparse parser = argparse.ArgumentParser() parser.add_argument('-x', dest = 'xxx', required = True) parser.add_argument('-y', dest = 'yyy', default ='') clarguments = vars(parser.parse_args()) print '-x value is ' + clarguments['xxx'] print '-y value is ' + clarguments['yyy']
The param required means that this program finished with failure if this argument wouldn't be passed.
The param dest means how to access this argument value in this script.
The param default means the default value if this argument wouldn't be passed as a commandline argument.