python road day8


1. Dynamically import modules
lib = __import__("lib.aa") 
c = lib.aa.C()
print(c.name)
print(lib.aa.C) #The

following is the commonly used method
import importlib
lib = importlib.import_module('lib. aa')
print(lib.C())


2. The assertion
is followed by a condition. If it is true, the following program will be executed. If not, an exception will be reported
. Example 1:

assert 6 == 6
print('6 equals 6')
There is no problem with the appeal, so the following content will be printed

Example 2:
assert type(2) is str 
print('g is str')
The assertion in the above example does not hold, so an error will be reported

Traceback (most recent call last):
File "/Users/luobiao/PycharmProjects/s14/day7/lib/aa.py", line 24, in <module>
assert type(2) is str
AssertionError

3. Write a simple socketssh client 
1) server-side code
import socket,os,time #Declare 

socket
server = socket.socket() #Bind
ip
server.bind(('localhost',6767))
#Listen
server.listen () #Wait
in a loop, and receive connections and Connection address

while True:
conn,addr = server.accept()
print(conn,addr)
while True: #Receive
data
data = conn.recv(1024) #Print
data and decode
print(data.decode() ) #Call
the popen module of os and call the command
d = os.popen(data.decode()).read()
length = str(len(d.encode()))
if len(d) == 0:
d = 'Command error, please re-enter.' #Return
message
conn.send(length.encode(encoding='utf-8'))
#The information sent twice by the socket sticky packet will be stuck together, resulting in an error in reception
#Solution 1: Use sleep to sleep for 0.5 seconds, let the buffer time out so that the two data are not in the same buffer
#time.sleep(0.5)
#Solution Scheme 2:
client_ack = conn.recv(1024)#Receive a data, let the client return information
print(client_ack.decode())
conn.send(d.encode(encoding='utf-8'))

server.close( )

2) Client code

import socket #Declare 

socket
client = socket.socket() #Specify the
connection address and port
client.connect(('localhost',6060)) #Send

the message in a loop
while True: #Let
the user enter information, imitating ssh input
message = input ('>>: ') #Send
a message, convert the data of type str to bytes, and use encode to convert
client.send(message.encode(encoding='utf-8')) #Receive
the message, and specify the maximum received The amount of data, in bytes
length = client.recv(1024).decode()
client.send('received size'.encode(encoding='utf-8'))
print(length) #Print
the message and convert it code
#print(length.decode())
recevied_size = 0
while int(length)> recevied_size:
data = client.recv(1024)
recevied_size +=len(data.decode())
print(data.decode())
print(recevied_size)
else:
print('Received') #Close
the link
client.close()




 



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325117933&siteId=291194637