Best Python code snippet using avocado_python
A3 Chat client.py
Source:A3 Chat client.py
...50 print("Error happened: ", e)51 return False525354def read_one_line(sock):55 """56 Read one line of text from a socket57 :param sock: The socket to read from.58 :return:59 """60 newline_received = False61 message = ""62 while not newline_received:63 character = sock.recv(1).decode()64 if character == '\n':65 newline_received = True66 elif character == '\r':67 pass68 else:69 message += character70 return message717273def get_servers_response():74 """75 Wait until a response command is received from the server76 :return: The response of the server, the whole line as a single string77 """78 global client_socket7980 try:81 server_answer = read_one_line(client_socket)82 return server_answer83 except IOError as e:84 print("Error happened: ", e)85 return False868788def connect_to_server():89 # Must have these two lines, otherwise the function will not "see" the global variables that we will change here90 global client_socket91 global current_state9293 client_socket = socket(AF_INET, SOCK_STREAM)9495 try:96 client_socket.connect((SERVER_HOST, TCP_PORT))97 current_state = "connected"98 send_command("sync", "")99 server_response = get_servers_response()100 if server_response == "modeok":101 print("Success. modeok recieved")102 else:103 print("Error. Message not returned as expected. Returned: ", server_response)104 return True105 except IOError as e:106 print("Error happened:", e)107 return False108109110def disconnect_from_server():111112 global client_socket113 global current_state114 try:115 client_socket.close()116 current_state = "disconnected"117 return True118 except IOError as e:119 print("error happened", e)120 return False121122123def login():124 global current_state125 global client_socket126127 try:128 username = input("Enter username: ")129 send_command("login", username)130 server_response = read_one_line(client_socket)131 if server_response == "loginok":132 print("Login successful. Logged inn as: ", username)133 current_state = "authorized"134 return True135 if server_response == "loginerr incorrect username format":136 print("Error. Username can only consist of alphanumeric characters: letters and digits. Try again")137 return False138 else:139 print("Error. Message not returned as expected. Returned: ", server_response)140 return False141142 except IOError as e:143 print("Error happened: ", e)144 return False145146147def public_message():148 global client_socket149150 try:151 message = input("Write the message you wish to send: ")152 send_command("msg", message)153 server_response = read_one_line(client_socket)154 server_response_splitted = server_response.split(" ")155 if server_response_splitted[0] == "msgok":156 print("Success. Message sent.")157 return True158 else:159 print("Error. Message not sent. Try again")160 return False161162 except IOError as e:163 print("Error! Not a valid username input. Start over.")164 return False165166167def get_user_list():168 global client_socket169 # protocol for users list: users\n170 try:171 send_command("users", "")172 string_users = read_one_line(client_socket)173 users_list = string_users.split(" ")174 # removing "users" at the start of the list175 del(users_list[0])176 print("Success. Received list of users: ", users_list)177178 except IOError as e:179 print("Error happened: ", e)180 return False181182183def private_message():184 global client_socket185186 try:187 recipient = input("Enter username of recipient: ")188 message = input("Enter message to be sent: ")189 recipient_and_message = recipient + " " + message190 send_command("privmsg", recipient_and_message)191 server_response = read_one_line(client_socket)192 server_response_splitted = server_response.split(" ")193 if server_response_splitted[0] == "msgok":194 if server_response_splitted[1] == "1":195 print("Success. Message sent")196 return True197 else:198 string_server_response = str(server_response_splitted[1])199 print("Success, but message was sent to %i recipients!" % string_server_response)200 return True201 elif server_response_splitted[0] == "msgerr":202 print("Error. Wrong recipient. Can't send to Anonymous users. Tried to send to: ", recipient)203 return False204 else:205 print("Error. Message was not sent. Server response: ", server_response)206 return False207208 except IOError as e:209 print("Error happened: ", e)210 return False211212213def inbox():214 global client_socket215216 try:217 send_command("inbox", "")218 server_answer = read_one_line(client_socket)219 server_answer_splitt = server_answer.split(" ")220 if server_answer_splitt[1] == "0":221 print("No new messages in inbox.")222 return True223 else:224 print("Your inbox has %i new messages." % int(server_answer_splitt[1]))225 for i in range(1, int(server_answer_splitt[1]) + 1):226 inbox_content = read_one_line(client_socket)227 inbox_content_splitted = inbox_content.split(" ")228 sender = inbox_content_splitted[1]229 del(inbox_content_splitted[0:2])230 messages = " "231 message = messages.join(inbox_content_splitted)232 print("Message %i is from " % i + sender + " and reads: " + message)233 return True234235 except IOError as e:236 print("Error happened: ", e)237 return False238239240"""
...
slow_log_stat.py
Source:slow_log_stat.py
...83 nb+=1.084 avg=total/nb85 print "SQL called {0} times, min time is {1}, max {2}, average {3}\n".format(nb,min(dict[i]),max(dict[i]),avg)86 #q=raw_input() 87def read_one_line():88 global lineread89 global line90 line=f.readline().rstrip()91 if line == "": closeandout()92 lineread+=193 94# This loop end when EOF is reached means readline return ""95lineread=096while 1:97 query=""98 read_one_line()99 # Read until find a query time tag100 if p_querytime.match(line):101 querytime=line.split(" ")[2]102 # if query time above longtime setting process it103 if float(querytime) > longtime:104 read_one_line()105 #exclude all line until timestamp106 while not p_timestamp.match(line):107 read_one_line()108 # Convert timestamp EPOCH format to human readable109 timestamp=re.split(p_timestamp,line)[1]110 timestamp=timestamp[:len(timestamp)-1]111 timestamp=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(timestamp)))112 read_one_line()113 # then read all lines until # for the query 114 while not line[0] == '#':115 query+=line.rstrip()116 read_one_line()117 query=re.sub(" +"," ",query)118 # If sorted is 0 then display 119 if sorted == 0 :120 print querytime+" : "+timestamp+" : "+query121 print122 # il sorted not 0 then build the rez dict.123 else:124 if query in rez:125 #print "\n EXIST "+querytime+query126 rez[query].append(querytime)127 #q=raw_input() 128 else:129 #print "\n NEW "+querytime+query130 rez.update({query:[querytime]})...
question2_by_w3.py
Source:question2_by_w3.py
1# 2. Write a Python program to read first n lines of a file2my_file=open("question_file2.txt","r")3read_one_line=my_file.readline()4print(read_one_line)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!