Python socket client/server select problems - python

We are attempting to make our python messenger system more efficient. Currently both the client and the server use ridiculous amounts of the CPU while running and communicating. We suspect this is due to the receiving/connecting loop trying constantly to receive a message or user/password.
the message receiving loop follows:
def recvmsg():
global decrypted_text
while not shutdown:
response = s.recv(4096).decode('utf-8')
response = decrypt(response)
if response.startswith("dict_keys(['"):
formatted = response.replace("dict_keys(['", "")
formatted = formatted.replace("'])", "")
formatted = formatted.replace("'", "")
output_field.configure(state = "normal")
output_field.insert(END, "Connected users: " + formatted + "\n")
output_field.see(END)
output_field.configure(state = "disabled")
else:
output_field.configure(state = "normal")
output_field.insert(END, response + "\n")
output_field.see(END)
output_field.configure(state = "disabled")
we are attempting to utilize the select module to have the loops wait for incoming traffic instead of looping and failing into infinity.
we have looked here: http://ilab.cs.byu.edu/python/select/echoserver.html for help but we didn't get very far because we got this error: [WinError 10022] An invalid argument was supplied. we also looked in the python documentation here: https://docs.python.org/3/library/select.html?highlight=select#module-select

You may find this answer to be helpful in implementing your server. If you wish for a more complete server implementation, that can be provided as well. In developing the complex version of the server, a variety of features were developed including friend lists, private messaging, and individual communication channels.
Simple_Server.py
#! /usr/bin/env python3
import socket, select
def main():
a = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)] # socket array
a[0].bind(('', 8989))
a[0].listen(5)
while True:
for b in select.select(a, [], [])[0]: # ready socket
if b is a[0]:
a.append(b.accept()[0])
else:
try:
c = b.recv(1 << 12) # sent message
except socket.error:
b.shutdown(socket.SHUT_RDWR)
b.close()
a.remove(b)
else:
for d in (d for d in a[1:] if d is not b): # message sink
d.sendall(c)
if __name__ == '__main__':
main()
MultichatClient.py
#! /usr/bin/env python3
from safetkinter import *
from tkinter.constants import *
import socket
import sys
class MultichatClient(Frame):
after_handle = None
def __init__(self, master, remote_host):
super().__init__(master)
self.message_area = ScrolledText(self, width=81, height=21,
wrap=WORD, state=DISABLED)
self.message_area.grid(sticky=NSEW, columnspan=2)
self.send_area = Entry(self)
self.send_area.bind('<Return>', self.keyPressed)
self.send_area.grid(sticky=EW)
b = Button(self, text='Send', command=self.mouseClicked)
b.grid(row=1, column=1)
self.send_area.focus_set()
try:
self.remote = socket.create_connection((remote_host, 8989))
except socket.gaierror:
print('Could not find host {}.'.format(remote_host))
except socket.error:
print('Could not connect to host {}.'.format(remote_host))
else:
self.remote.setblocking(False)
self.after_handle = self.after_idle(self.dataready)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
#classmethod
def main(cls, args):
root = Tk()
root.title('MultichatClient version 1.0')
m = cls(root, args[0])
m.grid(sticky=NSEW)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
root.mainloop()
return 1
def dataready(self):
try:
s = self.remote.recv(1 << 12).decode()
except socket.error:
pass
else:
self.message_area['state'] = NORMAL
self.message_area.insert(END, s)
self.message_area['state'] = DISABLED
self.message_area.see(END)
self.after_handle = self.after(100, self.dataready)
def destroy(self):
if self.after_handle:
self.after_cancel(self.after_handle)
super().destroy()
def mouseClicked(self, e=None):
self.remote.sendall(self.send_area.get().encode() + b'\r\n')
self.send_area.delete(0, END)
keyPressed = mouseClicked
if __name__ == '__main__':
sys.exit(MultichatClient.main(sys.argv[1:]))

Related

Cannot connect the python application with sockets properly to a public IP address

I developed a simple chat app that allows users to connect to a server and chat. This is the code for the server.
import os
from datetime import datetime
def log_file_name():
n = str(datetime.now())
m = n.replace(':','_').replace(' ','---')
l = m.split('.')[0]
l = f'{l}.txt'
return l
HOST = '127.0.0.1'
PORT = 10001
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print(type(server_socket))
server.bind((HOST, PORT))
server.listen()
print('server_initiated...')
logfile = os.path.join('logs', log_file_name())
with open(logfile, 'w') as fh:
fh.write(f'{str(datetime.now())} log file initiated!\n\n')
clients = []
nicknames = []
#broadcast
def broadcast(message):
#print(clients)
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
#print(f'{nicknames[clients.index(client)]} says {message}')
broadcast(message)
with open(logfile, 'a') as fh:
fh.write(f"{nicknames[clients.index(client)]} says {message.decode('utf-8')}\n")
except Exception:
index = clients.index(client)
clients.remove(client)
client.close()
left_nick = nicknames[index]
leaving_notes = f"{left_nick} just left the chat!! -- time {str(datetime.now()).split(' ')[1].split('.')[0]}"
broadcast(leaving_notes.encode('utf-8'))
with open(logfile,'a') as fh:
fh.write(f'{leaving_notes}\n')
nicknames.remove(left_nick)
break
#recieve message
def recieve():
while True:
client, address = server.accept()
#print(dir(client))
#print(client._io_refs)
#print(f'Connected with {str(address)}!!')
with open(logfile, 'a') as fh:
fh.write(f'Connected with {str(address)}!!\n')
client.send('Nickname'.encode('utf-8'))
nickname = client.recv(512).decode('utf-8')
nicknames.append(nickname)
clients.append(client)
#print(f'from 1st step clients are {clients}')
#print(f'Nickname of the client is {nickname}')
with open(logfile, 'a') as fh:
fh.write(f'Nickname of the client is {nickname}\n')
broadcast(f'Notice from server!! {nickname} just connected to the server!\n'.encode('utf-8'))
client.send(f'Connected to the server as {nickname}\n'.encode('utf-8'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
recieve()
Then I exposed that port to public using ngrok (ngrok http 10001), and it generated a public ip for me.
I coded a simple client gui using tkinter and I tried to connect the socket in to to above ngrok server I got. But I cannot broadcast messages. When I try to broadcast a message the GUI automatically closes. The reason is it meets a ConnectionAbortError.
Code for client-
import threading
import tkinter
import socket
import tkinter.simpledialog
import tkinter.scrolledtext
import os
#HOST = socket.gethostbyname(socket.gethostname())
#PORT = 10001
HOST = '3a7d-2402-4000-1245-cd8a-5d64-9c3f-25a3-79a4.in.ngrok.io'
PORT = 443 #or 80
class Client:
def __init__(self,host,port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
msg = tkinter.Tk()
msg.withdraw()
self.nickname = tkinter.simpledialog.askstring('Nickname', 'Please enter a nickname', parent=msg)
self.gui_done = False
self.running = True
gui_t=threading.Thread(target=self.gui_loop)
recieve_t=threading.Thread(target=self.recieve)
gui_t.start()
recieve_t.start()
def gui_loop(self):
self.win = tkinter.Tk()
self.win.configure(bg='lightgray')
self.chat_label = tkinter.Label(self.win, text='Chat:', bg='lightgray')
self.chat_label.config(font=('Arial',12))
self.chat_label.pack(padx=20, pady=5)
self.text_area = tkinter.scrolledtext.ScrolledText(self.win)
self.text_area.pack(padx=20,pady=5)
#self.text_area.config(state='disabled')
self.msg_label = tkinter.Label(self.win, text='Message:', bg='lightgray')
self.msg_label.config(font=('Arial', 12))
self.msg_label.pack(padx=20, pady=5)
self.input_area = tkinter.Text(self.win, height=3)
self.input_area.pack(padx=20, pady=5)
self.send_button = tkinter.Button(self.win, text='Send', command=self.write)
self.send_button.config(font=('Arial', 12))
self.send_button.pack(padx=20, pady=5)
self.gui_done = True
self.win.protocol('WM_DELETE_WINDOW', self.stop)
self.win.mainloop()
def write(self):
message = f"{self.nickname}: {self.input_area.get('1.0', 'end')}"
#print(message)
self.sock.send(message.encode('utf-8'))
self.input_area.delete('1.0','end')
def recieve(self):
while self.running:
try:
message = self.sock.recv(1024).decode('utf-8')
print(message)
if message == 'Nickname':
self.sock.send(self.nickname.encode('utf-8'))
else:
if self.gui_done:
#print('I hit here often')
self.text_area.config(state='normal')
self.text_area.insert('end', message)
self.text_area.yview('end')
#self.text_area.config(status='disabled') #never use this inside a loop, disabled blocks the code....
except ConnectionAbortedError: #when closed the window I come here..
print('Am i here?')
#break
os._exit(0)
#break
except:
break
print('Error')
self.sock.close()
break
def stop(self):
self.running = False
self.win.destroy()
self.sock.close()
exit(0)
client = Client(HOST, PORT)
If you run this please make sure to create a directory called logs to save the log of communication. Or else it will give an error(You can try it on localhost). I think I am doing something that doesn't work here. Can you point it out to me? or can you give me an alternative way of doing it?

Constantly update data from a server and print to a text box

So, I have a server completely written in Python 2.7:
from socket import *
from select import *
HOST = "127.0.0.1"
PORT = 1993
server = socket(AF_INET, SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
clients = []
def getClients():
to_use = []
for client in clients:
to_use.append(client[0])
return to_use
while(True):
read, write, error = select([server],[],[],0)
if(len(read)):
client, address = server.accept()
clients.append([client, address, []])
to_use = getClients()
try:
read, write,error = select(to_use,[],[],0)
if(len(read)):
for client in read:
data = client.recv(1024)
print(bytes.decode(data))
if(data == 0):
for c in clients:
if c[0] == client:
clients.remove(c)
break
else:
for c in clients:
c[2].append(data)
except:
pass
try:
to_use = getClients()
read, write, error = select([], to_use, [], 0)
if(len(write)):
for client in write:
for c in clients:
if c[0] == client:
for data in c[2]:
sent = client.send(data)
if(sent == len(data)):
c[2].remove(data)
break
except:
pass
What I need to do is get constant updates for data (messages) from the
server and print them to a text box made in Tkinter.
The receiving code:
from socket import *
from select import *
HOST = "127.0.0.1"
PORT = 1993
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((HOST, PORT))
while True:
data = bytes.decode(sock.recv(1024))
print data
It doesn't have to be Tkinter, but that's what I have been trying in; as long as it uses a GUI. Don't worry about sending messages I just need to be able to receive the data and print it to the text box/area.
The basic framework is to first create all of the widgets. Next, write a function that reads the data and updates the UI. Finally, arrange to have this function called every few milliseconds.
Roughly speaking, it looks something like this:
import Tkinter as tk
...
class Example(object):
def __init__(self):
self.root = tk.Tk()
self.text = tk.Text(root)
self.text.pack(fill="both", expand=True)
...
def start(self):
self.read_periodically()
self.root.mainloop()
def read_periodically(self):
# read the data
data = bytes.decode(sock.recv(1024))
# update the UI
self.text.insert("end", data)
# cause this function to be called again in 100ms
self.after(100, self.read_periodically)
example = Example()
example.start()
If the data is not a steady stream which causes sock.recv(1024) to block, your UI will freeze while it's waiting for data. If that's the case, you can move the reading of the socket to a thread, and have the thread communicate with the GUI via a thread-safe queue.
If the data is in a steady stream, or you set up a non-blocking socket, you don't have to do any of that.
I wanted to submit a comment first, but give this a try:
You can use something other than a start button to get things going I just put it there for ease of use
from Tkinter import *
import threading
from socket import *
from select import *
master = Tk() #create the GUI window
#put the test program in a seperate thread so it doesn't lock up the GUI
def test_program_thread():
thread = threading.Thread(None, test_program, None, (), {})
thread.start()
def test_program():
HOST = "127.0.0.1"
PORT = 1993
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((HOST, PORT))
while True:
data = bytes.decode(sock.recv(1024))
terminal_listbox.insert(END, str(data))
master.update() #I don't think this line is necessary, but put it here just in case
# set the gui window dimensions and the title on the GUI
master.minsize(width=450, height=450)
master.wm_title("Stack Problem")
# Start button is set to y and starts the test program when hit
start_button = Button(master, text='START', command=test_program_thread)
start_button.place(x=5, y=5)
# scroll bar for the terminal outputs
scrollbar = Scrollbar(master)
scrollbar.place(x=420, y=150)
# Terminal output. Auto scrolls to the bottom but also has the scroll bar incase you want to go back up
terminal_listbox = Listbox(master, width=65, height=13)
terminal_listbox.place(x=5, y=100)
terminal_listbox.see(END)
scrollbar.config(command=terminal_listbox.yview)
#GUI loops here
master.mainloop()

Cant send from server socket to client socket using python

I have a server and a client and they can connect to each other and I can send from the client to the server but not vice versa. The program fails when i'm trying to send back data to the client.
client.py
from tkinter import *
import socket
import threading
tLock = threading.Lock()
shutdown = False
host = '::1';
port = 5000;
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
class Application(Frame):
def __init__(self, master=None):
#Create master frame
Frame.__init__(self,master)
self.grid()
self.master.title("Test 1")
self.conn=False #State of connection to server
#Configure main frame
for r in range (4):
self.master.rowconfigure(r, weight=1)
for c in range (2):
self.master.columnconfigure(c)
#Create sub frames
TopFrame=Frame(master)
TopFrame.grid(row=0, column=0, rowspan=3)
BottomFrame=Frame(master, bg="green")
BottomFrame.grid(row=4, column=0, rowspan=3)
SideFrame=Frame(master, bg="red")
SideFrame.grid(column=1, row=0, rowspan=4)
#Create Chat log
self.chatlog=Text(TopFrame)
self.chatlog.pack(padx=5, pady=5)
#messenger and send button
self.e1=Entry(BottomFrame, width=92)
self.e1.pack(side=LEFT, pady=5, padx=5)
sendButton=Button(BottomFrame, text="Send", command=self.sendmessage, height = 1, width = 10)
sendButton.pack(side=LEFT)
#Create connect disconnect buttons
b1=Button(SideFrame, text="Connect", command=self.connect)
b1.grid(row=0, column=0, padx=5, pady=5)
b2=Button(SideFrame, text="Disconnect", command=self.disconnect)
b2.grid(row=1, column=0, padx=5, pady=5)
def connect(self): #Connect to server
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===ATTEMPTING TO CONNECT TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
s.connect((host,port))
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, (s))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("\n\n PLEASE ENTER A USER NAME AND SEND"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=True
print("Connected") #Connection successful
# M- Adding threading for receiving messages
rT = threading.Thread(target=self.receving, args=("RecvThread",s))
rT.start()
# When attempting to connect a second time, produces OS error: an operation was attempted on something that is not a socket
def disconnect(self):
if self.conn: #Tests to see if client is connected
s.close()
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===DISCONNECTED FROM SERVER.\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=False
else: #Prevents attempting to disconnect when already disconnected
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===YOU AREN'T CURRENTLY CONNECTED.\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
def sendmessage(self):
if self.conn: #Prevents sending if not connected
self.msg=self.e1.get()
if self.msg == "": #Empty message catcher
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===YOU CANNOT SEND AN EMPTY MESSAGE.\n" ))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
else:
self.send_data(self.msg) #Sends message to the server
self.e1.delete(0, END)
else:
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===YOU ARE NOT CONNECTED TO A SERVER. YOU CANNOT SEND A MESSAGE.\n" ))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
# M- Method to handle receiving from the server
# adds the data to the chat log.
def receving(self, name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, (data + '\n'))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
except:
pass
finally:
tLock.release()
def send_data(self, message):
try:
s.send(message.encode('UTF-8'))
except:
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===THE PREVIOUS MESSAGE DIDN'T SEND. THIS IS POSSIBLY DUE TO A SERVER ERROR.\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
root = Tk()
app = Application(root)
app.mainloop()
Server.py
import socket
import threading
import sys
hosts=["::1"]
port=5000
#dictionay to hold the socket as the key and the user name as the value
dic = {}
class Server:
def __init__ (self,hosts,port):
self.host=hosts
self.port=port
self.socketserver=socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.socketserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Socket has been created successfully")
for i in hosts:
try:
host=i
self.socketserver.bind((host,port))
print("Connection succeded to address",i)
print ("The server is now binded to the following IP address",host,"Port",port)
break
except socket.error:
print("Connection failed to address",i)
else:
sys.exit()
def Accept_connections(self):
while True:
self.socketserver.listen(10)
print("Socket is now awaiting connections")
server, clientaddress = self.socketserver.accept()
print("Connection enstablished with: " +str(clientaddress))
threading.Thread(target = self.message,args = (server,clientaddress),).start()
def message(self,server,clientaddress):
while True:
try:
data= server.recv(1024)
print("data ", data)
#check to see if it is a new socket that is not in the stored
#socket dictionary
if server not in dic.keys():
print("if statement")
#if it is a new socket
#add the socket and the user name
dic[server] = data
for key in dic:
#send the joined message to the users
print("failing")
key.send("\n\n" + data + " has joined the chat")
else:
#alias is a variable used to store the sockets username
alias = dic[server]
for key in dic:
#send the message to the sockets in the dictionary
key.send(alias + ": " +data)
except:
server.close()
#edit this bit !
print("Data transfer failed")
return False
Server(hosts,port).Accept_connections()
The program fails at:
key.send("\n\n" + data + " has joined the chat")
When a client connects they enter a user name to be known as. This stores it with a socket in a dictionary. The error occurs when looping round the sockets to inform the other clients they have joined. Any help would be brilliant. This was working on python27 but has now stopped when i updated to python34.
Managed to find the fix. When I upgraded to 3 the sending stopped working as it was trying to send strings. Python 3 requires bytes to be sent.
key.send(data + b' joined')
Was the solution

Python | How would I put this into multiple threads and allow the GUI to update?

I'm working on a sub alert system with a GUI, the problem I'm having is the GUI freezes because I'm running a loop that checks chat.
How would I incorporate this existing GUI and Chat code into a system where the GUI won't freeze and the textfield will update with what console has.
# Import Resources #
import re
import socket
import importlib
from Tkinter import *
from modules.IRCCommands import *
recentSub= 'N/A'
# Close application #
def Close_Window():
frmMain.destroy()
# Main application #
def Start():
# List info in the shell #
terminal.insert('1.0', 'Subscriber Alert ver. 1.5 | Created & Modified by RubbixCube' + "\n")
terminal.insert("end", 'Important Information:' + "\n")
terminal.insert("end", 'HOST = ' + HOST + "\n")
terminal.insert("end", 'PORT = ' + str(PORT) + "\n")
for c in CHAN:
terminal.insert("end", 'CHAN = ' + c + "\n")
terminal.insert("end", '\n' + "\n")
terminal.insert("end", 'Chat:' + "\n")
frmMain.update_idletasks
## Define basic Functions ##
def get_sender(msg):
result = ""
for char in msg:
if (char == "!"):
break
if (char != ":"):
result += char
return result
def get_message(msg):
result = ""
i = 3
length = len(msg)
while i < length:
result += msg[i] + " "
i += 1
result = result.lstrip(':')
return result
## End Helper Functions ##
def parse_message(channel, user, msg):
if len(msg) >= 1:
msg = msg.split(' ')
frmMain.update_idletasks
con = socket.socket()
con.connect((HOST, PORT))
send_pass(con, PASS)
send_nick(con, NICK)
for c in CHAN:
join_channel(con, c)
data = ""
while True:
try:
data = data+con.recv(1024)
data_split = re.split("\r\n", data)
data = data_split.pop()
for line in data_split:
#print(line)
#line = str.rstrip(line)
line = str.split(line)
# Stay connected to the server #
if (len(line) >= 1):
if (line[0] == 'PING'):
send_pong(con, line[1])
if (line[1] == 'PRIVMSG'):
sender = get_sender(line[0])
message = get_message(line)
channel = line[2]
terminal.insert("end", sender + ": " + message + "\n")
frmMain.update_idletasks
# Welcome new subs #
if (sender == "rubbixcube"):
def excuteCommand(con, channel, user, message, isMod, isSub):
msg = str.split(message)
if re.match('\w* subscribed for \w* months in a row!', message):
recentSub = msg[0]
print(recentSub)
send_message(con, channel, 'Thanks for your continued contribution %s!' % msg[0])
elif re.match('\w* just subscribed!', message):
recentSub = msg[0]
print(recentSub)
send_message(con, channel, str.format('Welcome to the channel %s. Enjoy your stay!' % msg[0]))
elif (re.match('\w* viewers resubscribed while you were away!', message)):
send_message(con, channel, 'Thanks for subscribing!')
excuteCommand(con, channel, sender, message, False, False)
parse_message(channel, sender, message)
except socket.error:
print("Socket died")
except socket.timeout:
print("Socket timeout")
## GUI ##
# Start loop of program
frmMain = Tk()
app = Frame(frmMain)
app.grid()
# Configure GUI
frmMain.title('Subscriber Alert ver. 2.0')
frmMain.geometry('455x357')
frmMain.resizable(0,0)
# Button
start = Button(app, text=' Start ')
start['command'] = Start
start.grid(row=0, column=0, pady=5)
close = Button(app, text=' Exit ')
close['command'] = Close_Window
close.grid(row=0, column=2, pady=5)
# Label
sub_lbl = Label(app, text='Most Recent Subscriber:')
sub_lbl.grid(row=1, column=0, columnspan=2, pady=10, padx=5)
sub_lbl2 = Label(app, text=recentSub)
sub_lbl2.grid(row=1, column=1, columnspan=3, pady=10, padx=5)
# Console
terminal = Text(app, width=56, height=17, wrap=WORD)
terminal.grid(row=3, column=0, columnspan=3)
# End loop of Program
frmMain.mainloop()
Thanks
"GUI-freezes issues" are common questions with network applications in Python. Usually either your network socket or stream is callign a blocking or timeouts are set to long, pipes and io stream are not finished being flushed or you GUI's reactor is not setup to work with your network io reactor (mainloop).
Typical workarounds are threading network io often with queue.Queue(), or use a network package that supports events, as GUIs are event driven. Twisted and asyncio offer event driven io. Or as often provided now some GUI packages and networking packages have "reactors" (mainloops) that where written to work with other specific packages. Twisted has reactors for TKinter and wx for example.

Python action freezes the program

I have this little program I wrote, In it there is a class of methods, and a class that build the window (only one).
from Tkinter import *
from tkMessageBox import *
import socket
import platform ,sys
import subprocess
from multiprocessing.pool import ThreadPool
import Queue
import threading
class Methods(object):
def __init__(self):
#TODO : implement
pass
def getHostName(self):
try:
return socket.gethostname()
except:
return "ERROR :Could'nt get Hostname"
def getOperatingSystem(self):
try:
return platform.system() + " " + platform.release() + " " + platform.version() + " " + sys.getwindowsversion()[4]
except:
return "ERROR :Could'nt get Operating System"
def getHotFixes(self,queue):
try:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
myProcess = subprocess.Popen(
"wmic qfe get HotFixID, InstalledOn",
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
startupinfo = startupinfo)
out, error = myProcess.communicate()
full_list = out.splitlines()
result = ""
for item in full_list:
if item != "" and item != " ":
result += "%s \n" % item
out_number = len(result.splitlines()) - 1
a = "There Are %s Microsoft HotFixes Updates \n\n%s" % (out_number , result)
queue.put(a)
except:
return "ERROR :Could'nt get HotFixes"
#VISUAL
#This class will have an instance of Methods and call every action by itself.
class MainWindow(object):
def __init__(self):
self.root = Tk()
self.root.title('SAAP')
self.root.geometry('610x440+100+100')
#self.root.resizable(0,0)
self.methods = Methods()
def openHostName():
disableAllButtons(self)
result = self.methods.getHostName()
print result
self.textLabelString.set("Host Name")
self.textBox.config(state=NORMAL)
self.textBox.delete("1.0",END)
self.textBox.insert(INSERT,result)
self.textBox.config(state=DISABLED)
enableAllButtons(self)
def openOperatingSystem():
disableAllButtons(self)
result = self.methods.getOperatingSystem()
print result
self.textLabelString.set("Operating System")
self.textBox.config(state=NORMAL)
self.textBox.delete("1.0",END)
self.textBox.insert(INSERT,result)
self.textBox.config(state=DISABLED)
enableAllButtons(self)
def openHotFixes():
queue = Queue.Queue()
thread_ = threading.Thread(
target = self.methods.getHotFixes,
name='Thread1',
args=[queue],
)
thread_.start()
thread_.join()
result = queue.get()
disableAllButtons(self)
self.textLabelString.set("Microsoft Hotfixes")
self.textBox.config(state=NORMAL)
self.textBox.delete("1.0",END)
self.textBox.insert(INSERT,result)
self.textBox.config(state=DISABLED)
enableAllButtons(self)
#items decleration
self.actionLabel = Label(self.root, text = 'Actions',bg='blue',fg='white')
self.button1 = Button(self.root, text = 'Host Name' , command=openHostName)
self.button2 = Button(self.root, text = 'Operating System' , command = openOperatingSystem)
self.button3 = Button(self.root, text = 'Microsoft HotFixes' , command = openHotFixes)
self.button4 = Button(self.root, text = 'N4')
self.button5 = Button(self.root, text = 'Fi5o')
self.button6 = Button(self.root, text = 'C6y')
self.button7 = Button(self.root, text = '7')
self.button8 = Button(self.root, text = '8y')
self.button9 = Button(self.root, text = 'R9s')
self.button10 = Button(self.root, text = '10t')
self.button11 = Button(self.root, text = 'I11s')
self.textLabelString = StringVar()
self.textLabel = Label(self.root,bg='black',fg='white',width=60,textvariable=self.textLabelString)
self.textLabelString.set("Output")
self.textBox = Text(self.root,width=52)
self.textBox.insert(INSERT,"Here's the output")
self.textBox.config(state=DISABLED)
self.scrollBar = Scrollbar(self.root)
self.scrollBar.config(command=self.textBox.yview)
self.textBox.config(yscrollcommand=self.scrollBar.set)
#items placing
self.actionLabel.grid(row=0,column=0,sticky=W+E+N+S,pady=5)
self.button1.grid(row=1,column=0,padx=5,pady=5,sticky=W+E)
self.button2.grid(row=2,column=0,padx=5,pady=5,sticky=W+E)
self.button3.grid(row=3,column=0,padx=5,pady=5,sticky=W+E)
self.button4.grid(row=4,column=0,padx=5,pady=5,sticky=W+E)
self.button5.grid(row=5,column=0,padx=5,pady=5,sticky=W+E)
self.button6.grid(row=6,column=0,padx=5,pady=5,sticky=W+E)
self.button7.grid(row=7,column=0,padx=5,pady=5,sticky=W+E)
self.button8.grid(row=8,column=0,padx=5,pady=5,sticky=W+E)
self.button9.grid(row=9,column=0,padx=5,pady=5,sticky=W+E)
self.button10.grid(row=10,column=0,padx=5,pady=5,sticky=W+E)
self.button11.grid(row=11,column=0,padx=5,pady=5,sticky=W+E)
self.textLabel.grid(row=0,column=1,padx=10,pady=5)
self.textBox.grid(row=1,column=1,rowspan=11,pady=5)
self.scrollBar.grid(row=1,column=2,rowspan=11,sticky=N+S)
def disableAllButtons(self):
self.button1['state'] = DISABLED
self.button2['state'] = DISABLED
self.button3['state'] = DISABLED
self.button4['state'] = DISABLED
self.button5['state'] = DISABLED
self.button6['state'] = DISABLED
self.button7['state'] = DISABLED
self.button8['state'] = DISABLED
self.button9['state'] = DISABLED
self.button10['state'] = DISABLED
self.button11['state'] = DISABLED
def enableAllButtons(self):
self.button1['state'] = NORMAL
self.button2['state'] = NORMAL
self.button3['state'] = NORMAL
self.button4['state'] = NORMAL
self.button5['state'] = NORMAL
self.button6['state'] = NORMAL
self.button7['state'] = NORMAL
self.button8['state'] = NORMAL
self.button9['state'] = NORMAL
self.button10['state'] = NORMAL
self.button11['state'] = NORMAL
def main():
mainw = MainWindow()
mainw.root.mainloop()
if __name__ == "__main__":
main()
Now , My problem is when I press a button it needs to do something and then the output should appear on screen.
BUT, and here comes the but --
when the action takes a bit, it freezes the program until the action is done.
I want to make the program treat maybe the action as a different thread so it won't freeze.
I tried some stuff but it did not worked for me unfortunately ...
Any Help ?
Appreciated!
It is ok to execute your actions in separate threads, however you need to implement a
mechanism for signaling to your main thread (where Tk's loop is running) when actions
are finished, and to get the result(s).
One approach is to have a proper Action class, creating thread objects ; you pass
the method to execute and its arguments, then you start the thread - beforehand,
you register a callback that will be called in your Tk loop when action is finished.
In order to pass results from the thread to the callback, a Queue can be used:
import functools
class Action(threading.Thread):
def __init__(self, method, *args):
threading.Thread.__init__(self)
self.daemon = True
self.method=method
self.args=args
self.queue=Queue.Queue()
def run(self):
self.queue.put(self.method(*self.args))
def register_callback(self, tkroot, callback):
# to be called by Tk's main thread,
# will execute the callback in the Tk main loop
try:
result = self.queue.get_nowait()
except:
# set a timer, to check again for results within 100 milliseconds
tkroot.after(100, functools.partial(self.register_callback,
tkroot, callback))
else:
return callback(result)
EDIT: modification of the original example to show how to apply this to the getHotFixes
method
As an example, here is how to change getHotFixes accordingly:
class Methods(object):
...
def getHotFixes(self):
try:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
myProcess = subprocess.Popen("wmic qfe get HotFixID, InstalledOn",
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
startupinfo = startupinfo)
out, error = myProcess.communicate()
full_list = out.splitlines()
result = ""
for item in full_list:
if item != "" and item != " ":
result += "%s \n" % item
out_number = len(result.splitlines()) - 1
return "There Are %s Microsoft HotFixes Updates \n\n%s" % (out_number , result)
except:
return "ERROR :Could'nt get HotFixes"
Finally, in MainWindow you just need to call the getHotFixes method, register
a callback to do something useful with the result when it's finished using
register_callback and call start() to start the Action thread:
class MainWindow(object):
def __init__(self):
self.root = Tk()
...
def openHotFixes():
disableAllButtons(self)
action = Action(self.methods.getHotFixes)
action.register_callback(self.root, openHotFixesDone)
action.start()
def openHotFixesDone(result):
self.textLabelString.set("Microsoft Hotfixes")
self.textBox.config(state=NORMAL)
self.textBox.delete("1.0",END)
self.textBox.insert(INSERT,result)
self.textBox.config(state=DISABLED)
enableAllButtons(self)
Hope this helps.

Categories

Resources