So I have a file that works as a socket server and I need it to be in a class structure. I would like to know how you would do it. There are some global vars and non global vars so for example which type of those will be self. or be private.
The class should be Server with an init and all the methods should be included in the class. After the class is written the code needs to create Server object and run the essential methods
i.e:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
handle_new_connection()
handle_receive_data()
handle_sending_msgs()
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
handle_sending_msgs()
server_socket.close()
Here's the code:
import socket
import select
import datetime
def get_current_time():
"""Returns hh:mm"""
now = datetime.datetime.now()
time = str(now.hour) + ":" + str(now.minute)
return time
def get_name(user_socket):
"""Returns the name of the user_socket, if he is an admin he gets # before his name"""
name = sockets_names[user_socket]
if len(admins) != 0:
if user_socket in admins:
name = "#" + name
return name
def get_data_length(data):
"""Returns the length of the data as string with length 3"""
length = str(len(data))
while len(length) < 3:
length = "0" + length
return length
def get_socket_by_name(name):
"""Returns the socket with the name, if none exists return None"""
if len(sockets_names) != 0:
for socket_pair, socket_name in sockets_names.items():
if name == socket_name:
return socket_pair
return None
def get_admins_as_string():
admins_names_lst = []
for admin_socket in admins:
admins_names_lst.append(sockets_names[admin_socket])
return str(admins_names_lst)[1:-1]
def remove_socket(removed_socket):
open_sockets.remove(removed_socket)
if removed_socket in admins:
admins.remove(removed_socket)
del sockets_names[removed_socket]
def handle_new_connection():
for new_connection in rlist:
if new_connection is server_socket:
(new_socket, address) = server_socket.accept()
open_sockets.append(new_socket)
sockets_names[new_socket] = "Anonymous"
if len(admins) == 0:
admins.append(new_socket)
print("New Connection And Admin")
else:
print("New Connection")
def handle_receive_data():
for current_socket in rlist:
if current_socket is not server_socket:
data_length = int(current_socket.recv(3).decode('utf-8'))
data = current_socket.recv(data_length).decode('utf-8')
if data[0] == '/':
handle_commands(current_socket, data[1:])
else:
private_msgs.append((current_socket, "You: " + data))
if current_socket in muted_sockets:
private_msgs.append((current_socket, """"You are muted and so can't send msgs to everyone. You can
ask one of the admins to unmute you in a private msg"""))
else:
public_msgs.append((current_socket, get_name(current_socket) + ": " + data))
def handle_sending_msgs():
for message in public_msgs:
(sender_socket, data) = message
data = get_current_time() + " " + data
for receiver_socket in wlist:
if receiver_socket is not sender_socket:
receiver_socket.send(bytes(get_data_length(data), 'utf8'))
receiver_socket.send(bytes(data, 'utf8'))
if message in public_msgs:
public_msgs.remove(message)
for message in private_msgs:
(receiver_socket, data) = message
data = get_current_time() + " " + data
if receiver_socket in wlist:
receiver_socket.send(get_data_length(data).encode('utf-8'))
receiver_socket.send(data.encode('utf-8'))
if message in private_msgs:
private_msgs.remove(message)
if data.split(' ')[1] == "bye":
remove_socket(receiver_socket)
def handle_commands(current_socket, data):
command = data.split(' ')[0].lower()
data = ' '.join(data.split(' ')[1:])
if command == "exit":
public_msgs.append((current_socket, get_name(current_socket) + " left the chat."))
private_msgs.append((current_socket, "bye"))
print("Connection with " + get_name(current_socket) + " closed.")
elif command == 'rename' or command == 'setname':
if data not in sockets_names.values():
if data.lower() != "you" and data.lower() != "server" and data.lower()[0] != "#":
sockets_names[current_socket] = data
private_msgs.append((current_socket, "Your name has been successfully changed to " + data + "."))
else:
private_msgs.append((current_socket, data + " is not a valid name."))
else:
private_msgs.append((current_socket, "This name is already taken."))
elif command == 'setadmin' or command == "promote":
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
new_admin_socket = get_socket_by_name(data)
admins.append(new_admin_socket)
private_msgs.append((current_socket, data + " has been promoted to admin."))
public_msgs.append((current_socket, get_name(current_socket) + " promoted " + data + " to admin."))
else:
private_msgs.append((current_socket, "You don't have access to this command."))
elif command == 'kick' or command == 'remove':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
kicked_socket = get_socket_by_name(data)
private_msgs.append((current_socket, data + " has been successfully kicked and removed."))
public_msgs.append((current_socket, get_name(current_socket) + " kicked and removed " + data))
private_msgs.append((kicked_socket, get_name(current_socket) + " kicked you."))
private_msgs.append((kicked_socket, "bye"))
elif command == 'mute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
muted_socket = get_socket_by_name(data)
muted_sockets.append(muted_socket)
private_msgs.append((current_socket, data + " has been successfully muted."))
public_msgs.append((current_socket, get_name(current_socket) + " muted " + data))
private_msgs.append((muted_socket, get_name(current_socket) + " muted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'unmute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
unmute_socket = get_socket_by_name(data)
if unmute_socket not in muted_sockets:
private_msgs.append((current_socket, "This user isn't muted."))
else:
muted_sockets.remove(unmute_socket)
private_msgs.append((current_socket, data + " has been successfully unmuted."))
public_msgs.append((current_socket, get_name(current_socket) + " unmuted " + data))
private_msgs.append((unmute_socket, get_name(current_socket) + " unmuted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'msg' or command == 'message' or command == "prvmsg" or command == "privatemessage":
send_to_name = data.split(' ')[0]
data = ' '.join(data.split(' ')[1:])
if send_to_name not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
send_to_socket = get_socket_by_name(send_to_name)
private_msgs.append(
(current_socket, "You -> " + send_to_name + ": " + data))
private_msgs.append((send_to_socket, get_name(current_socket) + " -> " + send_to_name + ": " + data))
elif command == 'admin' or command == "admins" or command == "adminlist" or command == "adminslist":
private_msgs.append((current_socket, "Admins: " + get_admins_as_string()))
elif command == 'users' or command == "userslist" or command == 'user' or command == "userlist":
private_msgs.append((current_socket, "Users: " + str(sockets_names.values())[1:-1]))
elif command == 'help' or command == '?':
commands = """/rename <name> - change your name.\n/msg <user> <msg> - will send <msg> as a private massage that only <user>
can see.\n/users - returns the names of all the connected users.\n/admins - returns the names of all the connected admins.\n/exit -
will disconnect you.\n\nAdmins' Commends Only:\n/kick <user> - kick the <user> from the server.\n/promote <user> - will ser <user> to
be an admin.\nmute <user> - will no let him send public msgs, only privates.\nunmute <user> - will cancel the mute on this user."""
private_msgs.append((current_socket, "\nCommands:\n" + commands + "\n"))
else:
private_msgs.append((current_socket, command + " is not a valid command."))
def main():
global server_socket, open_sockets, sockets_names, admins, muted_sockets, public_msgs, private_msgs
global rlist, wlist, xlist
server_socket = socket.socket()
try:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
open_sockets = []
sockets_names = {}
admins = []
muted_sockets = []
public_msgs = []
private_msgs = []
while True:
rlist, wlist, xlist = select.select([server_socket] + open_sockets, open_sockets, [])
handle_new_connection()
handle_receive_data()
handle_sending_msgs()
finally:
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
handle_sending_msgs()
server_socket.close()
if __name__ == '__main__':
main()
Here is the solution:
import socket
import select
import datetime
open_sockets=[]
sockets_names= {}
admins = []
muted_sockets = []
public_msgs = []
private_msgs = []
global server_socket
global rlist, wlist, xlist
class Server:
def __init__(self):
server_socket = socket.socket()
try:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
while True:
rlist, wlist, xlist = select.select([server_socket] + open_sockets, open_sockets, [])
self.handle_new_connection()
self.handle_receive_data()
self.handle_sending_msgs()
finally:
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
self.handle_sending_msgs()
server_socket.close()
def get_current_time(self):
"""Returns hh:mm"""
now = datetime.datetime.now()
time = str(now.hour) + ":" + str(now.minute)
return time
def get_name(self,user_socket):
"""Returns the name of the user_socket, if he is an admin he gets # before his name"""
name = sockets_names[user_socket]
if len(admins) != 0:
if user_socket in admins:
name = "#" + name
return name
def get_data_length(self,data):
"""Returns the length of the data as string with length 3"""
length = str(len(data))
while len(length) < 3:
length = "0" + length
return length
def get_socket_by_name(self,name):
"""Returns the socket with the name, if none exists return None"""
if len(sockets_names) != 0:
for socket_pair, socket_name in sockets_names.items():
if name == socket_name:
return socket_pair
return None
def get_admins_as_string(self):
admins_names_lst = []
for admin_socket in admins:
admins_names_lst.append(sockets_names[admin_socket])
return str(admins_names_lst)[1:-1]
def remove_socket(self,removed_socket):
open_sockets.remove(removed_socket)
if removed_socket in admins:
admins.remove(removed_socket)
del sockets_names[removed_socket]
def handle_new_connection(self):
for new_connection in rlist:
if new_connection is server_socket:
(new_socket, address) = server_socket.accept()
open_sockets.append(new_socket)
sockets_names[new_socket] = "Anonymous"
if len(admins) == 0:
admins.append(new_socket)
print("New Connection And Admin")
else:
print("New Connection")
def handle_receive_data(self):
for current_socket in rlist:
if current_socket is not server_socket:
data_length = int(current_socket.recv(3).decode('utf-8'))
data = current_socket.recv(data_length).decode('utf-8')
if data[0] == '/':
self.handle_commands(current_socket, data[1:])
else:
private_msgs.append((current_socket, "You: " + data))
if current_socket in muted_sockets:
private_msgs.append((current_socket, """"You are muted and so can't send msgs to everyone. You can
ask one of the admins to unmute you in a private msg"""))
else:
public_msgs.append((current_socket, self.get_name(current_socket) + ": " + data))
def handle_sending_msgs(self):
for message in public_msgs:
(sender_socket, data) = message
data = self.get_current_time() + " " + data
for receiver_socket in wlist:
if receiver_socket is not sender_socket:
receiver_socket.send(bytes(self.get_data_length(data), 'utf8'))
receiver_socket.send(bytes(data, 'utf8'))
if message in public_msgs:
public_msgs.remove(message)
for message in private_msgs:
(receiver_socket, data) = message
data = self.get_current_time() + " " + data
if receiver_socket in wlist:
receiver_socket.send(self.get_data_length(data).encode('utf-8'))
receiver_socket.send(data.encode('utf-8'))
if message in private_msgs:
private_msgs.remove(message)
if data.split(' ')[1] == "bye":
self.remove_socket(receiver_socket)
def handle_commands(self,current_socket, data):
command = data.split(' ')[0].lower()
data = ' '.join(data.split(' ')[1:])
if command == "exit":
public_msgs.append((current_socket, self.get_name(current_socket) + " left the chat."))
private_msgs.append((current_socket, "bye"))
print("Connection with " + self.get_name(current_socket) + " closed.")
elif command == 'rename' or command == 'setname':
if data not in sockets_names.values():
if data.lower() != "you" and data.lower() != "server" and data.lower()[0] != "#":
sockets_names[current_socket] = data
private_msgs.append((current_socket, "Your name has been successfully changed to " + data + "."))
else:
private_msgs.append((current_socket, data + " is not a valid name."))
else:
private_msgs.append((current_socket, "This name is already taken."))
elif command == 'setadmin' or command == "promote":
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
new_admin_socket = self.get_socket_by_name(data)
admins.append(new_admin_socket)
private_msgs.append((current_socket, data + " has been promoted to admin."))
public_msgs.append((current_socket, self.get_name(current_socket) + " promoted " + data + " to admin."))
else:
private_msgs.append((current_socket, "You don't have access to this command."))
elif command == 'kick' or command == 'remove':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
kicked_socket = self.get_socket_by_name(data)
private_msgs.append((current_socket, data + " has been successfully kicked and removed."))
public_msgs.append((current_socket, self.get_name(current_socket) + " kicked and removed " + data))
private_msgs.append((kicked_socket, self.get_name(current_socket) + " kicked you."))
private_msgs.append((kicked_socket, "bye"))
elif command == 'mute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
muted_socket = self.get_socket_by_name(data)
muted_sockets.append(muted_socket)
private_msgs.append((current_socket, data + " has been successfully muted."))
public_msgs.append((current_socket, self.get_name(current_socket) + " muted " + data))
private_msgs.append((muted_socket, self.get_name(current_socket) + " muted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'unmute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
unmute_socket = self.get_socket_by_name(data)
if unmute_socket not in muted_sockets:
private_msgs.append((current_socket, "This user isn't muted."))
else:
muted_sockets.remove(unmute_socket)
private_msgs.append((current_socket, data + " has been successfully unmuted."))
public_msgs.append((current_socket, self.get_name(current_socket) + " unmuted " + data))
private_msgs.append((unmute_socket, self.get_name(current_socket) + " unmuted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'msg' or command == 'message' or command == "prvmsg" or command == "privatemessage":
send_to_name = data.split(' ')[0]
data = ' '.join(data.split(' ')[1:])
if send_to_name not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
send_to_socket = self.get_socket_by_name(send_to_name)
private_msgs.append(
(current_socket, "You -> " + send_to_name + ": " + data))
private_msgs.append((send_to_socket, self.get_name(current_socket) + " -> " + send_to_name + ": " + data))
elif command == 'admin' or command == "admins" or command == "adminlist" or command == "adminslist":
private_msgs.append((current_socket, "Admins: " + self.get_admins_as_string()))
elif command == 'users' or command == "userslist" or command == 'user' or command == "userlist":
private_msgs.append((current_socket, "Users: " + str(sockets_names.values())[1:-1]))
elif command == 'help' or command == '?':
commands = """/rename <name> - change your name.\n/msg <user> <msg> - will send <msg> as a private massage that only <user>
can see.\n/users - returns the names of all the connected users.\n/admins - returns the names of all the connected admins.\n/exit -
will disconnect you.\n\nAdmins' Commends Only:\n/kick <user> - kick the <user> from the server.\n/promote <user> - will ser <user> to
be an admin.\nmute <user> - will no let him send public msgs, only privates.\nunmute <user> - will cancel the mute on this user."""
private_msgs.append((current_socket, "\nCommands:\n" + commands + "\n"))
else:
private_msgs.append((current_socket, command + " is not a valid command."))
Just call the class:
ServerClass()
Related
i want to get info from the internet from a name (string) but its not working, here is my code:
import dox
AutoProccesFromPcName = dox:Resolve_name_of_base("Google Chrome.exe")
def FindInfo(name):
compose = dox.name(name)
netGlobalSearch = dox:FindMatchesForNetwork(AutoProccesFromPcName,compose)
numberOfResults = dox:ComposeFNumFrom(netGlobalSearch)
if numberOfResults > 0:
print("FOUND " + str(numberOfResults) + " RESULTS")
for index, result in netGlobalSearch:
if dox:PackInfo(dox:Compose(result)) != 0:
print("RESULT " + str(result) + " FOUND AT INDEX: " + str(index))
input("Press enter to exit program... ")
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
Im making an address book and i got a problem. It's telling me that I have a problem with str and lists. I'm new to python so i dont really know what to do.
Here is the full program:
print("\n This is your address book.")
import os
import time
saveFile = open("ContactList.txt", "r")
ContactsString = saveFile.read()
saveFile.close()
Contacts = ContactsString.split('\n')
while '' in Contacts:
Contacts.remove('')
def printContacts():
index = 1
for contact in Contacts:
print("{}: {}".format(index, contact))
index = index + 1
def addContact():
print("You have chosen to add a new contact into your address book.")
name = input("What's the contacts name? ")
counter = Contacts.count(name)
if counter == 0:
address = input("Enter the address of " + name + ': ')
email = input("Enter the email of " + name + ': ')
Contacts.append([ name, address, email ])
else:
print("The contact already exists in the address book.")
print("If you desire to change the contacts current information, enter nr 3 in the menu.")
def browseContacts():
print("You have chosen to view all your contacts with their name, address and email." "\n")
for i in range(0, len(Contacts), 3):
print(Contacts[i], Contacts[i + 1], Contacts[i + 2], '\n')
def searchContacts():
print("\n You have chosen to search up a specific contact.")
searchName = input("Enter the name of the contact that you want to search up: ")
searchFound = False
for i in range(0, len(Contacts), 3):
if searchName == Contacts[i]:
searchName = True
break
if searchFound == True:
print(Contacts[i], Contacts[i + 1], Contacts[i + 2], "\n")
else:
print("We couldn't find " + searchName + " in the address book.")
print("Check whether your spelling was correct or not.")
time.sleep(4)
def deleteContact():
print('\n You have chosen option 4, to delete a specific contact from your address book')
printContacts()
deletename = input(' Enter the name of the contact you wish to delete from your address book: ').title()
deletefound = False
for i in range(0, len(Contacts), 3): #finds the contact the user wants to delete. It only iterates through each third post so that it only goes through the names of the contact.
if deletename == Contacts[i]:
deletefound = True
break
if deletefound == True:
Contacts.pop(i) # deletes the contact information from the list
Contacts.pop(i)
Contacts.pop(i)
print('\n ' + deletename + 'has been removed from your address book')
else:
print('\n ' + deletename + "doesn't exist in the address book")
def modifyContacts():
print("You have chosen option 5, to update a specific contact in your address book.")
printContacts()
newName = input("Enter the name of the contact you wish to update: ")
modifyFound = False
for i in range(0, len(Contacts), 3):
if newName == Contacts[i]:
modifyFound = True
break
if modifyFound == True:
Contacts[i] = input(' Enter the new name of ' + newName + ': ')
Contacts[i + 1] = input(' Enter the new address of ' + Contacts[i] + ': ')
Contacts[i + 2] = input(' Enter the new e-mail of ' + Contacts[i] + ': ')
print('\n The contact has now been updated')
else:
print("\n " + newName + " doesn't exist in the address book")
print(" You can add " + newName + "to your address book by pressing 1 in the menu below")
time.sleep(4)
running = True
while running == True:
print('''
===================================================================
Menu:
1: Add new contact (press 1)
2: Show all contacts (press 2)
3: Show a specific contact (press 3)
4: Delete contact (press 4)
5: Update contact (press 5)
6: Quit program (press 6)
===================================================================''')
actionchoice = input('\n Please enter your choice of action: ')
if actionchoice == '1':
addContact()
elif actionchoice == '2':
browseContacts()
elif actionchoice == '3':
searchContacts()
elif actionchoice == '4':
deleteContact()
elif actionchoice == '5':
modifyContacts()
elif actionchoice == '6':
print('\n Shutting down. Thank you for using the adressbook! \n')
running = False
else:
print('\n The entered command does not exist within this program')
print(' Please enter one of the actions shown in the menu: \n')
time.sleep(4)
saveFile = open("ContactList.txt", "w")
for x in range(0, len(Contacts), 3):
saveFile.write("\n" + Contacts[x] + "\n")
saveFile.write( Contacts[x + 1] + "\n")
saveFile.write( Contacts[x + 2] + "\n")
saveFile.close()
The problem is in the end and the problem says:
Exception has occurred: TypeError
**can only concatenate str (not "list") to str**
File "C:\Users\Anvandare\Documents\Programmering1\Arbetet\addressbook.py", line 162, in <module>
saveFile.write("\n" + Contacts[x] + "\n")
In other words, this is the problem:
saveFile.write("\n" + Contacts[x] + "\n")
What am i supposed to do for it to work?
This line is wrong:
Contacts.append([ name, address, email ])
This is not appending each variable as a separate element of the list, it's creating a nested list in Contacts. It should be:
Contacts.append(name)
Contacts.append(address)
Contacts.append(email)
or:
Concacts += [ name, address, email ]
You also need to fix printContacts() to process Contacts in groups of 3, like the rest of the code.
def printContacts():
index = 1
for i in range(0, len(Contacts), 3):
print("{}: {} {} {}".format(index, *Contacts[i:i+3]))
index = index + 1
IMHO it would be better for Contacts to be a list of dictionaries, but doing this would require a rewrite to 90% of your code and I'm not going to do that here.
I learn Python and as a practice decided to write a server for a network game "Backgammon". The question arose as to make sure that found in the queue apponet still online? How to send a ping and accept the answer? I'm trying to do it on line 71, but this is incorrect.
import pymongo, socket, threading, string, json, MySQLdb, random, time
stat = True
conn = {}
#gamers = {}
games = {}
diceroll = []
tempconn = {}
c = pymongo.Connection()
db = c.nardy
nru = db.notregusers
uwait = db.userwait
class ClientThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def getUserId(self, data):
json_data = json.loads(data)
if json_data['t'] == 'n':
print ' - User not register'
if nru.find({'identuser':json_data['i'], 'platform':json_data['p']}).count() == 0:
print ' - New user'
count = nru.find().count();
newid = count + 1;
nru.save({'id':newid, 'identuser':json_data['i'], 'platform':json_data['p'], 'level':1})
return nru.find_one({'id':newid})
else:
print ' - Old user'
return nru.find_one({'identuser':json_data['i'], 'platform':json_data['p']})
elif json_data['t'] == 'r':
return 9999
def mySQLConnect(self):
db = MySQLdb.connect(host="localhost", user="", passwd="", db="", charset='utf8')
return db
def run(self):
while True:
data = self.channel.recv(1024)
try:
json_data = json.loads(data)
comm = json_data['c']
if comm == 'x':
if conn.has_key(gamer['level']) and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
self.channel.close()
break
elif comm == 'h':
gamer = self.getUserId(data)
self.gamer = gamer
elif comm == 'f':
lev = 0
findenemy = 1
while findenemy == 1:
if conn.has_key(gamer['level']):
lev = gamer['level']
elif conn.has_key((gamer['level'] - 1)):
lev = (gamer['level'] - 1)
elif conn.has_key((gamer['level'] + 1)):
lev = (gamer['level'] + 1)
if lev != 0:
if len(conn[lev]) > 0:
enemy = conn[lev].pop(0)
firsttime = time.time()
enemy.channel.send('{"o":"p"}')
while (firsttime + 30) > time.time() and findenemy == 1:
if comm == 'k':
findenemy = 0
print ' - Ping enemy: ok'
if findenemy == 0:
self.enemy = enemy
gameid = str(self.gamer['id']) + '_' + str(self.enemy.gamer['id'])
games[gameid] = {'dice':[], 'nextstep':0}
vrag = self.enemy
a = random.sample(range(1,7),2)
self.channel.send('{"o":"s", "u":"' + str(a[0]) + '", "e":"' + str(a[1]) + '"}')
vrag.channel.send('{"o":"s", "u":"' + str(a[1]) + '", "e":"' + str(a[0]) + '"}')
if a[0] > a[1]:
step = 1
games[gameid]['nextstep'] = self.gamer['id']
self.channel.send('{"o":"u"}')
vrag.channel.send('{"o":"w"}')
else:
step = 2
games[gameid]['nextstep'] = self.enemy.gamer['id']
self.channel.send('{"o":"w"}')
vrag.channel.send('{"o":"u"}')
tempconn[self.enemy] = self
else:
conn[lev].append(self)
findenemy = 0
self.channel.send('{"o":"q"}')
else:
conn[gamer['level']] = [self]
self.channel.send('{"o":"q"}')
elif comm == 'w':
if not hasattr(self, 'enemy'):
self.enemy = tempconn[self]
vrag = self.enemy
gameid = str(self.enemy.gamer['id']) + '_' + str(self.gamer['id'])
self.channel.send('{"o":"o"}')
elif comm == 'r' and games[gameid]['nextstep'] == self.gamer['id']:
dice = []
dice.append(self.gamer['id'])
dice.append(random.randint(1,6))
dice.append(random.randint(1,6))
games[gameid]['dice'].append(dice)
self.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
vrag.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
games[gameid]['nextstep'] = self.enemy.gamer['id']
elif comm == 'r' and games[gameid]['nextstep'] != self.gamer['id']:
self.channel.send('{"o":"w"}')
elif comm == 'm' and 't' in json_data:
self.channel.send('{"o":"y", "t":"' + str(json_data['text']) + '"}')
vrag.channel.send('{"o":"e", "t":"' + str(json_data['text']) + '"}')
elif comm == 's':
self.channel.send('{"o":"g", "countgame":"' + str(len(games)) + '"}')
elif comm == 'q' and 's' in json_data and 'e' in json_data:
print " - Player step"
elif comm == 'b' and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
except ValueError:
continue
print 'Closed connection:', self.details[0]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8088))
server.listen(5)
while stat:
channel, details = server.accept()
ClientThread(channel, details).start()
Perhaps, in addition to answering the question, you give me some recommendations ...
There are two options for you to send out a ping and get response.
Use scapy. Use sendp function to send a ping and get response.
Use os.system to invoke command line to send a ping and get response. Like os.system('ping 127.0.0.1')
Hope it helps.:)
I'm attempting to convert names from a first name first style to a family name first. The trick is getting it to accept input with or without a middle name.
My code as it stands:
import re
def convertName(oldName):
newName = oldName
while newName == oldName:
newName = re.sub('^ +', '',oldName)
newName = re.sub(' +', ' ',newName)
return newName
def main(firstName, middleName, lastName):
finalName = (lastName + firstName + middleName)
return finalName
name = 0
while name != "":
name = str(input("Name ---- "))
if name == "":
print("Finished")
break
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
finalMiddleName = " " + middleName[0] + '.'
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
My current results:
Name ---- joshua example example
Result -- example, joshua e.
Name ---- joshua example
Traceback (most recent call last):
line 37, in 0
builtins.IndexError: string index out of range
Any tips/hints would be much appreciated!!
Eventually found out a working solution in the following:
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
if middleName != "":
finalMiddleName = " " + middleName[0] + '.'
else:
finalMiddleName = ""
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
Or you could just do the following:
name = str(input("Name ---- "))
if len(name.split()) == 2:
print("Result -- " + name[name.rfind(" "):] + ", " + name[:name.find(" ")] + " " + name[name.find(" ")+1] + ".")
if len(name.split()) == 1:
print ("Result -- " + name[name.find(" "):] + ", " + name[:name.find(" ")])
else:
print ("Sorry! Invalid name")
This implementation has only been tested in Python 2.7.5.
It uses the string methods .find() and .rfind() to find the indices of the start of the first name, middle name, and last name
len(name.split()) tests how many words are in the name.
Your problem:
string = ""
print(string[0])
returns an error.
so, I fixed your main function, but you'll have to re-write the parser:
def main(firstName, lastName, middleName=""):
if(middleName == ""):
finalName = (lastName + " " + firstName)
else:
finalName = lastName + " " + firstName + " " + middleName[0] + "."
return finalName