Python Route Nine

Source: Internet
Author: User

Paramiko

Paramiko module is a module written in Python language, follow the SSH2 protocol, support the remote server connection in the way of encryption and authentication

SSH execution Command:


Import Paramiko
SSH = Paramiko. Sshclient ()
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
Ssh.connect (hostname= ' 192.168.155.8 ', port=22,username= ' root ', password= ' 19890131 ')
stdin, stdout, stderr = Ssh.exec_command (' ls ')
STD, err = Stdout.read (), Stderr.read ()
result = STD If std else err
Print (Result.decode ())
Ssh.close ()

Upload, download file:

Import Paramiko

Transport = Paramiko. Transport (("192.168.155.9", 22))
Transport.connect (username= "root", password= "19870924")
SFTP = Paramiko. Sftpclient.from_transport (transport)

Sftp.put ("C:/users/hxzli/desktop/111.txt", "/tmp/111.txt")

# Sftp.get ("Remove_path", "Local_path")

Transport.close ()

Python Threading Module

Python's explanatory language also has a dedicated threading model, and Python virtual machines use the Gil (Global interpreter lock, globe interpreter Lock) to mutually exclusive threads access to shared resources, but are temporarily unable to take advantage of multiprocessor benefits.

In Python we are mainly through the thread and threading these two modules, wherein the Python threading module is to do some packaging thread, can be more convenient to use, so we use The threading module implements multithreaded programming.

At the language level, Python provides very good support for multithreading, allowing you to easily support the creation of threads, mutexes, semaphores, and synchronization. The following is the official online Introduction threading module basic information and functions:
Implementation module

Thread: Multithreading of the underlying support module, generally not recommended to use;

Threading: Thread is encapsulated, and some threads are manipulated.
Threading Module

Thread threading class, this is the most we use a class, you can specify the thread function execution or inherit from it can implement sub-threading function;

A timer is similar to a thread, but waits for a period of time before it starts to run;

Lock the primitive, which we can use when the global variable is mutually exclusive;

Rlock can re-enter the lock, so that the single-threaded can obtain the acquired lock again;

Condition A conditional variable that allows a thread to stop waiting for another thread to satisfy a certain "condition";

The condition variable that is common to the Event. Multiple threads can wait for an event to occur, and all threads are activated after the event occurs;

Semaphore provides a structure similar to the "Waiting Room" for the thread that waits for the lock;

Boundedsemaphore is similar to semaphore, but is not allowed to exceed the initial value;

Queue: Implements multi-producer (Producer), multi-Consumer (Consumer) queues, supports lock primitives, and provides good synchronization support across multiple threads.
where the thread class

Is your primary threading class and you can create process instances. The functions provided by this class include:

GetName (self) Returns the name of the thread

The IsAlive (self) Boolean flag that indicates whether the thread is still running

Isdaemon (self) Returns the daemon flag for the thread

The Join (self, timeout=none) program hangs until the thread ends and, if a timeout is given, blocks timeout seconds

Run (self) defines the function function of the thread

Setdaemon (self, daemonic) sets the thread's daemon flag to Daemonic

SetName (self, name) sets the name of the thread

Start (self) starts thread execution
Where queue provides the class

Queue queues

Lifoqueue after in first out (LIFO) queue

Priorityqueue Priority Queue

A simple multithreaded instance:

Import threading
Import time
def run (N):
Print (' Task ', N)
Time.sleep (2)
T1 = Threading. Thread (target=run,args= (' T1 ',))
T2 = Threading. Thread (target=run,args= (' T2 ',))
T1.start ()
T2.start ()

Queue queues

In Python, queues are the most common form of exchanging data between threads. The queue module is a module that provides queued operations, although it's easy to use, but if you're not careful, there are some surprises.

Create a "queue" object
Import Queue
Q = queue.queue (maxsize = 10)
The Queue.queue class is a synchronous implementation of a queue. The queue length can be unlimited or limited. The queue length can be set through the optional parameter maxsize of the queue's constructor. If MaxSize is less than 1, it means that the queue length is infinite.

Put a value in the queue
Q.put (10)
The put () method of the call queue object inserts an item at the end of the team. Put () has two parameters, the first item is required, the value of the inserted item, and the second block is an optional parameter, which defaults to
1. If the queue is currently empty and the Block is the 1,put () method, the calling thread pauses until a data cell is vacated. If the block is the 0,put method, the full exception is thrown.

Take a value out of the queue
Q.get ()
The Get () method of the call queue object is removed from the team header and returns an item. The optional parameter is block, which is true by default. If the queue is empty and the Block is True,get (), the calling thread is paused until a project is available. If the queue is empty and the block is false, the queue throws an empty exception.

The Python queue module has three types of queues and constructors:
1, the Python queue module FIFO queuing first-out. Class Queue.queue (MaxSize)
2, LIFO similar to the heap, that is, advanced after out. Class Queue.lifoqueue (MaxSize)
3, there is a priority queue level lower the more first out. Class Queue.priorityqueue (MaxSize)

Common methods in this package (q = Queue.queue ()):
Q.qsize () returns the size of the queue
Q.empty () returns True if the queue is empty, and vice versa false
Q.full () returns True if the queue is full, otherwise false
Q.full corresponds to maxsize size
Q.get ([block[, timeout]]) Get queue, timeout wait time
Q.get_nowait () quite q.get (False)
Non-blocking Q.put (item) write queue, timeout wait time
Q.put_nowait (item) quite Q.put (item, False)
Q.task_done () After completing a work, the Q.task_done () function sends a signal to the queue that the task has completed
Q.join () actually means waiting until the queue is empty before performing another operation

Producer Consumer Model

Using producer and consumer patterns in concurrent programming can solve most concurrency problems. This mode improves the overall processing speed of the program by balancing the productivity of the production line and the consuming thread.

Why use producer and consumer models

In the world of threads, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. To solve this problem, the producer and consumer models were introduced.

What is the producer consumer model

The producer-consumer model solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, balancing the producers and consumers Processing capacity.

Instance:

#-*-Coding:utf-8-*-
Import threading
Import queue

Def producer ():
For I in range (10):
Q.put ("Bone%s"% i)
Print ("Start waiting for all bones to be taken away ...")
Q.join ()
Print ("All bones are finished ...")


def consumer (N):

While Q.qsize () >0:

Print ("%s fetch"%n, Q.get ())
Q.task_done () #告知这个任务执行完了


Q = queue. Queue ()



p = Threading. Thread (Target=producer,)
P.start ()

C1 = Consumer ("Chen Ronghua")

Python Route Nine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.