Python Learning notes (i)

Source: Internet
Author: User

         

1. Netstat-no This command is to look at the port, and you can see through the PID which programs are using these ports!


2 in Python or in other languages, using sockets to write server and client communication programs often encounters an error:
Socket.error: [Errno 10048] typically each socket address (Protocol/network address/port) is allowed only once this prompt appears when port conflicts occur, possibly because after creating a socket in the server program opens a port, The socket was not closed at the end of the program, so the next

This error message will appear at the start of the program, Workaround: 1, close the socket 2 at the end of the server program, or replace the port number 3, restart the machine


3 ipconfig View the IP of this machine


4. Attributeerror: ' Module ' object has no attribute "Funsalaryguide" This error is believed to be encountered by many Django developers. In general, the application is not installed, re-installation will be done


A 5.PYC file, which is a python-compiled bytecode (bytecode) file. As soon as you run the py file, the Python compiler will automatically generate a corresponding PYC bytecode file. This PYC bytecode file, after the Python interpreter, generates machine code to run (which is why PYC files can be deployed across platforms,

A Java-like cross-platform, a bytecode file run by the JVM in Java). The next call calls PYc directly, without invoking the py file. Until you have changed this py file. The Python interpreter checks the build time in the PYc file to compare the modification time of the Py file and, if the PY is updated, generates a new PYC.


6.t = MyThread (2)

Traceback (most recent):
File "<pyshell#0>", line 1, in <module>
t = MyThread (2)
File "C:\Users\bsamsung\Desktop\Python27\ thread \join.py", line 7, in __init__
Theading. Thread.__init__ (self)
Nameerror:global name ' theading ' is not defined

Like this, Python does not compile the program ahead of time, she runs first, and when she encounters something wrong, it starts to stop.

The 7.accept method returns a tuple containing two elements (connection,address). The first element, connection, is the new socket object that the server must communicate with the customer, and the second element address is the customer's Internet location.


The 8.xrange usage is exactly the same as range, and the difference is not a list object but a generator.

9. if __name__ = = ' main ' in Python:

Statement to enter the module you want to use.
Each module has a built-in variable __name__. When the module runs itself, the __name__ is equal to ' main ', and if it is import by another module, the module's __name__ is equal to the module name, which is the part of the filename that removes the py extension.

Here's an example:
test.py
def test ():
Print "Test is running"

if __name__ = = "__main__": #自运行时调用该程序块
Print "Test main is working"

if __name__ = = "Test": #import时调用该程序块
Print "Test is invoked"


10. Non-blocking or asynchronous programming

For example, for a chat room, because there are multiple connections that need to be processed at the same time, it is clear that blocking or synchronizing the method is not appropriate, it is like a ticket to open a window, like Blake many people line up and so on. So how do we solve this problem? There are three main methods: Forking, threading, asynchronous

/ o.

The method of forking and threading is very simple and can be achieved by using the Min-in class of the Socketserver service class. Forking only applies to UNIX-like platforms; threading need to be aware of memory sharing issues.
asynchronous I/O is a bit difficult to implement if the underlying method is implemented. To be simple, consider using a framework or twisted in a standard library (twisted is a very powerful framework for asynchronous network programming).

First, the realization of forking and threading with Scoketserver

Here we use two examples to create forking servers and threading servers, respectively.

Forking server:

From Socketserver import TCPServer, Forkingmixin, Streamrequesthandler

Class Server (Forkingmixin, tcpserver): Pass

Class Handler (Streamrequesthandler):
def handle (self):
addr = Self.request.getpeername ()
print ' Got connection from ', addr
Self.wfile.write (' Thank for connecting ')

Server = Server ((' ', 1234), Handler)
Server.serve_forever ()

Threading Server:

From Socketserver import TCPServer, ThreadingMixIn, Streamrequesthandler

Class Server (ThreadingMixIn, tcpserver): Pass

Class Handler (Streamrequesthandler):
def handle (self):
addr = Self.request.getpeername ()
print ' Got connection from ', addr
Self.wfile.write (' Thank for connecting ')

Server = Server ((' ', 1234), Handler)
Server.serve_forever ()

Ii. using Select to implement asynchronous I/O

The so-called asynchronous I/O, for example, is that if a large group of people want you to listen to him, then you give them each a minute of time to say, we take turns to say, did not finish the next turn to continue to say. A method of a time slice.

To implement asynchronous I/O, we can use the framework Asyncore/asynchat or twisted, which are based on the SELECT function or the poll function (poll is only suitable for UNIX-like systems). Both the Select and poll functions come from the Select module.

The SELECT function requires three must-sequences as parameters and an optional time-out value in seconds. The sequence is an integer value representing the file descriptor, which is the connection we are waiting for. These three sequences are about input, output, and exception conditions. If the timeout value is not given, select will be in a blocked state (

That is, wait until there is a file descriptor to prepare the action. If the timeout value is given, then select only blocks the given time. If the timeout value is 0, then it will not block. The value returned by select is a tuple of three sequences that represent a subset of the activity of the corresponding parameter. For example, the first sequence

Returns a sequence of input file descriptors that are used for reading.

The sequence can contain file objects (not Windows) or sockets. The following example creates a server that uses select to serve several connections (note: The socket on the service side also provides a select to enable it to signal when a new connection is ready to be accepted). This server is just

Simply print the data that is accepted from the client. You can use Telnet (or write a simple socket-based client) to connect to test it.

Select Server

Import socket, select

s = Socket.socket ()
Host = Socket.gethostname ()
Port = 1234
S.bind ((host, Port))

S.listen (5)
inputs = [s]
While True:
RS, ws, ES = select.select (inputs, [], [])
For R in RS:
If R is s:
C, addr = S.accept ()
print ' Got connection from ', addr
Inputs.append (c)
Else
Try
data = R.RECV (1024)
disconnected = Not data
Except Socket.error:
disconnected = True

If disconnected:
Print r.getpeername (), ' Disconnected '
Inputs.remove (R)
Else
Print data


Each python is a thread that supports multithreading and is native. This is achieved mainly through the two modules of thread and threading. Python's thread module is a relatively low-level module, Python's threading module is a thread to do some packaging, can be more convenient to use. Generally speaking

There are two modes of using threads, one is to create a function to execute the thread, pass the function into the thread object, let it execute, and the other is to inherit directly from thread, create a new class, and put the code executed by the thread into the new class.

12 What can I do with python? Can do daily tasks, such as automatic backup of your MP3, can do website, many famous websites including YouTube is written by Python, can do online game backstage, many online game backstage are developed by Python. It's a lot of things to be able to do anyway.

Python, of course, does not have the ability to do things, such as writing the operating system, which can only be written in C language, mobile phone applications, only with Objective-c (for the iphone) and Java (for Android), write 3D games, preferably in C or C + +.


13 Operating systems rotate each task alternately, Task 1 executes 0.01 seconds, switches to Task 2, Task 2 executes 0.01 seconds, switches to task 3, executes 0.01 seconds ... This is done repeatedly. On the surface, each task is executed alternately, but because the CPU is running too fast, we feel

Like all tasks are executed at the same time. True parallel multitasking can only be done on multicore CPUs, but because the number of tasks is much larger than the number of cores in the CPU, the operating system automatically shifts many tasks to each core.


14. One is to start multiple processes, each of which has only one thread, but multiple processes can perform multiple tasks in one piece.

Another way is to start a process that starts multiple threads within a process, so that multiple threads can perform multiple tasks in one piece.

Of course, there is a third way, that is, to start multiple processes, each process to start more than one thread, so that the simultaneous execution of more tasks, of course, this model is more complex, and rarely used.

A thread is the smallest execution unit, and a process consists of at least one thread. How to schedule processes and threads is entirely up to the operating system, and the program itself cannot decide when to execute and how long it takes to execute.

Multi-process and multi-threaded programs involve synchronization, data sharing issues, and are more complex to write.

Python Learning notes (i)

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.