Found 10476 Articles for Python

Multithreaded Priority Queue in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:24:30

1K+ Views

The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue −get() − The get() removes and returns an item from the queue.put() − The put adds item to a queue.qsize() − The qsize() returns the number of items that are currently in the queue.empty() − The empty( ) returns True if queue is empty; otherwise, False.full() − the full() returns True if queue is full; otherwise, False.Example#!/usr/bin/python import Queue import threading import time exitFlag = 0 class myThread (threading.Thread):    def __init__(self, threadID, name, q): ... Read More

Synchronizing Threads in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:21:11

11K+ Views

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.The release() method ... Read More

The Threading Module in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:18:04

11K+ Views

The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.The threading module exposes all the methods of the thread module and provides some additional methods −threading.activeCount() − Returns the number of thread objects that are active.threading.currentThread() − Returns the number of thread objects in the caller's thread control.threading.enumerate() − Returns a list of all thread objects that are currently active.In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows −run()  − The run() method is the entry point ... Read More

Starting a New Thread in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:08:18

488 Views

To spawn another thread, you need to call following method available in thread module −thread.start_new_thread ( function, args[, kwargs] )This method call enables a fast and efficient way to create new threads in both Linux and Windows.The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.Here,  args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.Example#!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay):    count = 0   ... Read More

Sending Attachments as an E-mail using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:09:56

704 Views

To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.ExampleFollowing is the example, which sends a file /tmp/test.txt as an attachment. Try it once −#!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and ... Read More

Sending an HTML e-mail using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:05:04

754 Views

When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.ExampleFollowing is the example to send HTML content as an e-mail. Try it once −#!/usr/bin/python import smtplib message = """From: From Person To: ... Read More

Database Handling Errors in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:03:40

4K+ Views

There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.Sr.No.Exception & Description1WarningUsed for non-fatal issues. Must subclass StandardError.2ErrorBase class for errors. Must subclass StandardError.3InterfaceErrorUsed for errors in the database module, not the database itself. Must subclass Error.4DatabaseErrorUsed for errors in the database. Must subclass Error.5DataErrorSubclass of DatabaseError that refers to errors in the data.6OperationalErrorSubclass of DatabaseError ... Read More

Disconnecting Database in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:02:53

6K+ Views

To disconnect Database connection, use close() method.db.close()If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

Commit & RollBack Operation in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:02:15

660 Views

COMMITCommit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.Here is a simple example to call commit method.db.commit()ROLLBACKIf you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.Here is a simple example to call rollback() method.db.rollback()

Performing Database Transactions using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:01:40

1K+ Views

Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −Atomicity − Either a transaction completes or nothing happens at all.Consistency − A transaction must start in a consistent state and leave the system in a consistent state.Isolation − Intermediate results of a transaction are not visible outside the current transaction.Durability − Once a transaction was committed, the effects are persistent, even after a system failure.The Python DB API 2.0 provides two methods to either commit or rollback a transaction.ExampleYou already know how to implement transactions. Here is again similar example −# Prepare SQL query to DELETE required records sql ... Read More

Advertisements