working on it ...


Explore Public Snippets

Sort by

Found 85k snippets matching: python

    public by vietkute02 modified Dec 29, 2013  1544176  273  5  2

    convert suds response to dictionary

    from suds.sudsobject import asdict
    def recursive_asdict(d):
        """Convert Suds object into serializable format."""
        out = {}
        for k, v in asdict(d).iteritems():
            if hasattr(v, '__keylist__'):
                out[k] = recursive_asdict(v)
            elif isinstance(v, list):
                out[k] = []
                for item in v:
                    if hasattr(item, '__keylist__'):
                out[k] = v
        return out
    def suds_to_json(data):
        return json.dumps(recursive_asdict(data))

    public by lbottaro modified Mar 18, 2014  1191746  42  7  0

    Using lambda function to pass extra argument to slots using PyQt4 python

    When programming with PyQt is useful to pass extra arguments to slots callback methods, in order to execute some code when a UI control's action is invoked. In this example you can see the usage of lambda expression to pass the extra argument to the method invoked when pressing a button. Thanks to
    self.greeting = QLabel('', self)
    # Create the build button with its caption
    self.build_button = QPushButton('&Build Greeting', self)
    # Connect the button's clicked signal to AddControl
    self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
    def AddControl(self, name):
        self.greeting.setText('%s!' % (name))

    public by marksimon232 modified Aug 8, 2014  1002187  29  5  3

    How to add Cookies and Headers in HTTP requests in Python

    Let's say I have an HTTP GET request and I want to decorate it with some Headers (e.g. "Accept" or "Authorization") and with some Cookies. What's the best way to do this in Python?
    => According to the api -, the headers can all be passed in using requests.get:
    r=requests.get("", headers={"content-type":"text"});
    => Response Headers:
    We can view the server’s response headers using a Python dictionary:
    >>> r.headers
        'status': '200 OK',
        'content-encoding': 'gzip',
        'transfer-encoding': 'chunked',
        'connection': 'close',
        'server': 'nginx/1.0.4',
        'x-runtime': '148ms',
        'etag': '"e1ca502697e5c9317743dc078f67693f"',
        'content-type': 'application/json; charset=utf-8'
    => HTTP Headers are case-insensitive, so we can access the headers using any
    capitalization we want.
    >>> r.headers['Content-Type']
    'application/json; charset=utf-8'
    >>> r.headers.get('content-type')
    'application/json; charset=utf-8'
    # If a header doesn’t exist in the Response, its value defaults to None:
    >>> r.headers['X-Random']
    => Cookies
    If a response contains some Cookies, you can get quick access to them:
    >>> url = ''
    >>> r = requests.get(url)
    >>> r.cookies['requests-is']
    # To send your own cookies to the server, you can use the cookies parameter:
    >>> url = ''
    >>> cookies = dict(cookies_are='working')
    >>> r = requests.get(url, cookies=cookies)
    >>> r.text
    '{"cookies": {"cookies_are": "working"}}'

    public by lbottaro modified Oct 30, 2013  903618  36  7  0

    How to parse the JSON result of a jenkins job in python

    This snippet shows how to get and parse the JSON format of the last execution of a Jenkins job. You have to specify: Jenkins_server - The Jenkins server name/IP address http_port - The port used by Jenkins server job_name - The job name
    import urllib2
    import json 
    def getBuildResult():
            jenkinsStream    = urllib2.urlopen(jenkins_job_dir)
        except urllib2.HTTPError, e:
            print "URL Error: " + str(e.code) 
            return "FAILURE"
            buildStatusJson = json.load( jenkinsStream )
            print "Failed to parse json"
            return "FAILURE"
        if buildStatusJson.has_key( "result" ):      
            print "build status job " + buildStatusJson["result"]
            if buildStatusJson["result"] != "SUCCESS" :
                return "FAILURE"
            return "FAILURE"
        return "SUCCESS"
    print "loading"
    print "Done"

    public by lbottaro modified Oct 24, 2013  644673  11  7  2

    Using Pickle to Save Objects in Python - String Serialization

    You can use the pickle module to save data in a serialized format, typically in a txt string, performing what is better known as data serialization, marshalling, or flattening. Pickle allows you to save an object to a file for later retrieval. Pickling some data will write the python object (dictionary, list, tuple, class) as one long strea
    import pickle 
    # The data to save
    myDict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    # The object to pickle
    object_pi = myDict 
    # The file where to write the serialized string
    file_pi = open('filename_pi.obj', 'w')
    # Dump the data as string to file 
    pickle.dump(object_pi, file_pi)

    public by lbottaro modified Oct 30, 2013  564583  12  7  2

    How to create a simple GUI in python using PyQt4

    In this example, we create a simple window using PyQt4 and its QtGui module. Thanks to
    import sys
    from PyQt4 import QtGui
    def main():
        # Every PyQt4 application must create an application object.
        # The application object is located in the QtGui module.
        app = QtGui.QApplication(sys.argv)
       # The QWidget widget is the base class of all user interface objects in PyQt4.
       # We provide the default constructor for QWidget. The default constructor has no parent.
        # A widget with no parent is called a window.
        w = QtGui.QWidget()
        # The resize() method resizes the widget.
        w.resize(250, 150)
        w.move(300, 300)
        # Here we set the title for our window.
        # The show() method displays the widget on the screen.
        # Finally, we enter the mainloop of the application.
    if __name__ == '__main__':

    public by lbottaro modified Oct 30, 2013  599034  19  7  0

    How to create a simple button in python using GUI PyQt4

    Using PyQt4 python module, you can easily add a QtGui.QPushButton as interactive button in your mask. Constructor QPushButton(string text, QWidget parent = None). The 'text' parameter is the text displayed on the button. The 'parent' is a widget, onto which we place the button. Thanks to
    import sys
    from PyQt4 import QtGui, QtCore
    class GUI_Example(QtGui.QWidget):
        def __init__(self):
            super(GUI_Example, self).__init__()
        def initUI(self):               
            qbtn = QtGui.QPushButton('Quit', self)
            qbtn.move(55, 55)       
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Quit button')    
    def main():
        app = QtGui.QApplication(sys.argv)
        ex = GUI_Example()
    if __name__ == '__main__':

    public by lbottaro modified Feb 13, 2014  539358  9  7  1

    How to check if a Git remote repository is available in python

    This simple python code shows how to check if a given Git remote repository is available. The code invokes the git command 'git ls-remote' on the remote URL path as subprocess with Popen and checks the exit code, using the communicate() method. The command exit status is stored into the 'returncode' property. A value not-equals to '0' mean
    from subprocess import Popen, PIPE, STDOUT
    p = Popen(["git", "ls-remote", "git://remote_path"], stdout=PIPE)
    output = p.communicate()[0]
    if p.returncode != 0:
      print "Command failed ["+str(p.returncode)+"]"        

    public by fabio.nosenzo @ Amazon_AWS_Python_API modified Aug 1, 2013  586741  5  7  0

    Amazon S3 Aws - S3Connection object from python boto API

    This snippet is about the S3Connection object provided by python boto package for Amazon AWS API. Here the __init__ method is listed with all its variables. The AWSAuthConnection object is initialized and it handles all the data for managing requests and response from Amazon AWS service. Path: [boto/s3/] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', '')
        DefaultCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.SubdomainCallingFormat')
        QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
        def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                     is_secure=True, port=None, proxy=None, proxy_port=None,
                     proxy_user=None, proxy_pass=None,
                     host=DefaultHost, debug=0, https_connection_factory=None,
                     calling_format=DefaultCallingFormat, path='/',
                     provider='aws', bucket_class=Bucket, security_token=None,
                     suppress_consec_slashes=True, anon=False,
            if isinstance(calling_format, str):
            self.calling_format = calling_format
            self.bucket_class = bucket_class
            self.anon = anon
            AWSAuthConnection.__init__(self, host,
                    aws_access_key_id, aws_secret_access_key,
                    is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
                    debug=debug, https_connection_factory=https_connection_factory,
                    path=path, provider=provider, security_token=security_token,

    public by lbottaro @ Amazon_AWS_Python_API modified Aug 4, 2013  570477  13  7  0

    Amazon S3 Aws - How to get content information for a given bucket using boto python api

    This snippet shows how to iterate through your own Amazon S3 buckets and list the available content.
    import boto
    import boto.s3.connection
    access_key = '<aws access key>'
    secret_key = '<aws secret key>'
    # This code initialize the Amazon S3 connection to your account
    conn = boto.connect_s3(
            aws_access_key_id = access_key,
            aws_secret_access_key = secret_key)
    # Iteration through all available buckets stored into S3
    # Name and creation date are listed
    for bucket in conn.get_all_buckets():
            print "{name}\t{created}".format(
                    name =,
                    created = bucket.creation_date,
            # For each bucket get all data content put into the bucket
            for key in bucket.list():
                    # Get name, size and date
                    print "{name}\t{size}\t{modified}".format(
                            name =,
                            size = key.size,
                            modified = key.last_modified,
    • Public Snippets
    • Channels Snippets