Calling wxPython.NotificationMessage every specified time - python-3.x

I have written function to check every user-specified time for updates and if there any, to display notification message about it.
My code:
def show_notification():
notification_bubble = wx.App()
wx.adv.NotificationMessage("", "sample notification").Show()
notification_bubble.MainLoop()
def update():
# retrieve var from newest_porcys_url_imported
first_porcys_url = newest_porcys_url_imported()
# retrieve var from newest_pitchfork_url_imported
first_pitchfork_url = newest_pitchfork_url_imported()
# fetch newest review url with get_porcys_review_url
get_latest_porcys_url_ = get_porcys_review_url()
get_latest_porcys_url = get_latest_porcys_url_[0]
# fetch newest review url with get_pitchfork_review_url
get_latest_pitchfork_url_ = get_pitchfork_review_url()
get_latest_pitchfork_url = get_latest_pitchfork_url_[0]
a = first_porcys_url + ' ' + get_latest_porcys_url
b = first_pitchfork_url + ' ' + get_latest_pitchfork_url
get_datetime = datetime.now()
hour = str(get_datetime.hour)
minutes = str(get_datetime.minute)
f = open('log.txt', 'a')
f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n')
f.close()
if first_porcys_url != get_latest_porcys_url or first_pitchfork_url != get_latest_pitchfork_url:
print('new reviews')
f = open('new reviews.txt', 'a')
f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n')
f.close()
return True
else:
show_notification()
return False
My problem is that it only displays the notification one time and after that it doesn't do anything, including executing update function. I replaced call_function() with print instruction for testing and everything worked fine, so calling that function is causing troubles.

The Problem is your show_notification() function. The line:
notification_bubble.MainLoop()
will only finish once the window is closed. So what's happening is that once your show_notification() function is called, you go into a loop waiting for the user to close the window. But if he does, then the program exits. So it is impossible to call show_notification() more than once.
wxPython Documentation on MainLoop()
I don't know much about wxPython but I expect that you might have to get into threading.
Threading Tutorial
You would start a new thread for each notification like this:
import threading
def show_notification():
notification_bubble = wx.App()
wx.adv.NotificationMessage("", "sample notification").Show()
notification_bubble.MainLoop()
def update():
# retrieve var from newest_porcys_url_imported
first_porcys_url = newest_porcys_url_imported()
# retrieve var from newest_pitchfork_url_imported
first_pitchfork_url = newest_pitchfork_url_imported()
# fetch newest review url with get_porcys_review_url
get_latest_porcys_url_ = get_porcys_review_url()
get_latest_porcys_url = get_latest_porcys_url_[0]
# fetch newest review url with get_pitchfork_review_url
get_latest_pitchfork_url_ = get_pitchfork_review_url()
get_latest_pitchfork_url = get_latest_pitchfork_url_[0]
a = first_porcys_url + ' ' + get_latest_porcys_url
b = first_pitchfork_url + ' ' + get_latest_pitchfork_url
get_datetime = datetime.now()
hour = str(get_datetime.hour)
minutes = str(get_datetime.minute)
f = open('log.txt', 'a')
f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n')
f.close()
if first_porcys_url != get_latest_porcys_url or first_pitchfork_url != get_latest_pitchfork_url:
print('new reviews')
f = open('new reviews.txt', 'a')
f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n')
f.close()
return True
else:
notificationThread = threading.Thread(target=show_notification)
# Prepare the thread
notificationThread.daemon = True
# Make shure it will run in the background
notificationThread.start()
# Start the thread
return False
That way, each notification is a background process while your main program can keep on running.
I hope I could help. Have a nice day!

You would have to wrap the whole thing into the mainloop:
This simple app creates a blocking message, if you want a non-blocking or self cancelling message, that is a completely different kettle of fish!
import wx
import time
def Alerts(x):
#Do your stuff here rather than sleeping
time.sleep(2)
dlg = wx.MessageBox("New Message "+str(x),"My message heading",wx.OK | wx.ICON_INFORMATION)
if __name__ == "__main__":
A1 = wx.App()
#This could be a while True loop
for x in range(10):
Alerts(x)
A1.MainLoop()

Related

How do I save the extracted Email IDs in an excel sheet using Python, that too in a row?

outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
your_folder = mapi.Folders['email#outlook.com'].Folders['Blah']
blah_inbox = your_folder.Items
f = open("email_txt.csv", "w")
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress)
else:
print(message.SenderEmailAddress)
I opened a new fie and wrote it to a csv, but I get the following result.
user1#outlook.comuser2#outlook.comuser3#outook.com.....
However, I need the result to be like the below
user1#outlook.com
user2#outlook.com
user3#outlook.com
The Simple solution is the following
f = open("email_txt.csv", "w")
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress + '\n')
else:
print(message.SenderEmailAddress)
I added a "\n" to the end of the write command
Alternatively, since my whole intention was to save in a CSV with some sort of headers. Below is what worked for me. This is the entire code.
Todays_Mail = dt.datetime.now() - dt.timedelta(hours=24)
Todays_Mail = Todays_Mail.strftime('%m/%d/%Y %H:%M %p')
# Connect to Outlook inbox
outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
your_folder = mapi.Folders['email'].Folders['Blah']
blah_inbox = your_folder.Items
blah_inbox = blah_inbox.Restrict("[ReceivedTime] >= '" + Todays_Mail + "'")
f = open("email.csv", "w")
f.write('Emails,Index\n')
index = 0
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress + ',' + str(index) + '\n')
index = index + 1
else:
print(message.SenderEmailAddress)
f.close()
The above will give you two columns, one with the header Email, and the second would be a column with the header Index.

Keep getting else/elif invalid syntax error

Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")

MaybeEncodingError: Error sending result: '<multiprocessing.pool.ExceptionWithTraceback object at 0x0000018F09F334A8>'

I am getting the below error when I am downloading files using multiprocessing. I am downloading Wikipedia page views and they have it by hour so it might include a lot of downloading.
Any recommendation to why this error is caused and HOW TO SOLVE IT? Thanks
MaybeEncodingError: Error sending result:
''. Reason: 'TypeError("cannot serialize
'_io.BufferedReader' object",)'
import fnmatch
import requests
import urllib.request
from bs4 import BeautifulSoup
import multiprocessing as mp
def download_it(download_file):
global path_to_save_document
filename = download_file[download_file.rfind("/")+1:]
save_file_w_submission_path = path_to_save_document + filename
request = urllib.request.Request(download_file)
response = urllib.request.urlopen(request)
data_content = response.read()
with open(save_file_w_submission_path, 'wb') as wf:
wf.write(data_content)
print(save_file_w_submission_path)
pattern = r'*200801*'
url_to_download = r'https://dumps.wikimedia.org/other/pagecounts-raw/'
path_to_save_document = r'D:\Users\Jonathan\Desktop\Wikipedia\\'
def main():
global pattern
global url_to_download
r = requests.get(url_to_download)
data = r.text
soup = BeautifulSoup(data,features="lxml")
list_of_href_year = []
for i in range(2):
if i == 0:
for link in soup.find_all('a'):
lien = link.get('href')
if len(lien) == 4:
list_of_href_year.append(url_to_download + lien + '/')
elif i == 1:
list_of_href_months = []
list_of_href_pageviews = []
for loh in list_of_href_year:
r = requests.get(loh)
data = r.text
soup = BeautifulSoup(data,features="lxml")
for link in soup.find_all('a'):
lien = link.get('href')
if len(lien) == 7:
list_of_href_months.append(loh + lien + '/')
if not list_of_href_months:
continue
for lohp in list_of_href_months:
r = requests.get(lohp)
data = r.text
soup = BeautifulSoup(data,features="lxml")
for link in soup.find_all('a'):
lien = link.get('href')
if "pagecounts" in lien:
list_of_href_pageviews.append(lohp + lien)
matching_list_of_href = fnmatch.filter(list_of_href_pageviews, pattern)
matching_list_of_href.sort()
with mp.Pool(mp.cpu_count()) as p:
print(p.map(download_it, matching_list_of_href))
if __name__ == '__main__':
main()
As Darkonaut proposed. I used multithreading instead.
Example:
from multiprocessing.dummy import Pool as ThreadPool
'''This function is used for the download the files using multi threading'''
def multithread_download_files_func(self,download_file):
try:
filename = download_file[download_file.rfind("/")+1:]
save_file_w_submission_path = self.ptsf + filename
'''Check if the download doesn't already exists. If not, proceed otherwise skip'''
if not os.path.exists(save_file_w_submission_path):
data_content = None
try:
'''Lets download the file'''
request = urllib.request.Request(download_file)
response = urllib.request.urlopen(request)
data_content = response.read()
except urllib.error.HTTPError:
'''We will do a retry on the download if the server is temporarily unavailable'''
retries = 1
success = False
while not success:
try:
'''Make another request if the previous one failed'''
response = urllib.request.urlopen(download_file)
data_content = response.read()
success = True
except Exception:
'''We will make the program wait a bit before sending another request to download the file'''
wait = retries * 5;
time.sleep(wait)
retries += 1
except Exception as e:
print(str(e))
'''If the response data is not empty, we will write as a new file and stored in the data lake folder'''
if data_content:
with open(save_file_w_submission_path, 'wb') as wf:
wf.write(data_content)
print(self.present_extract_RC_from_RS + filename)
except Exception as e:
print('funct multithread_download_files_func' + str(e))
'''This function is used as a wrapper before using multi threading in order to download the files to be stored in the Data Lake'''
def download_files(self,filter_files,url_to_download,path_to_save_file):
try:
self.ptsf = path_to_save_file = path_to_save_file + 'Step 1 - Data Lake\Wikipedia Pagecounts\\'
filter_files_df = filter_files
self.filter_pattern = filter_files
self.present_extract_RC_from_RS = 'WK Downloaded-> '
if filter_files_df == '*':
'''We will create a string of all the years concatenated together for later use in this program'''
reddit_years = [2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]
filter_files_df = ''
'''Go through the years from 2005 to 2018'''
for idx, ry in enumerate(reddit_years):
filter_files_df += '*' + str(ry) + '*'
if (idx != len(reddit_years)-1):
filter_files_df += '&'
download_filter = list([x.strip() for x in filter_files_df.split('&')])
download_filter.sort()
'''If folder doesn't exist, create one'''
if not os.path.exists(os.path.dirname(self.ptsf)):
os.makedirs(os.path.dirname(self.ptsf))
'''We will get the website HTML elements using beautifulsoup library'''
r = requests.get(url_to_download)
data = r.text
soup = BeautifulSoup(data,features="lxml")
list_of_href_year = []
for i in range(2):
if i == 0:
'''Lets get all href available on this particular page. The first page is the year page'''
for link0 in soup.find_all('a'):
lien0 = link0.get('href')
'''We will check if the length is 4 which corresponds to a year'''
if len(lien0) == 4:
list_of_href_year.append(url_to_download + lien0 + '/')
elif i == 1:
list_of_href_months = []
list_of_href_pageviews = []
for loh in list_of_href_year:
r1 = requests.get(loh)
data1 = r1.text
'''Get the webpage HTML Tags'''
soup1 = BeautifulSoup(data1,features="lxml")
for link1 in soup1.find_all('a'):
lien1 = link1.get('href')
'''We will check if the length is 7 which corresponds to the year and month'''
if len(lien1) == 7:
list_of_href_months.append(loh + lien1 + '/')
for lohm in list_of_href_months:
r2 = requests.get(lohm)
data2 = r2.text
'''Get the webpage HTML Tags'''
soup2 = BeautifulSoup(data2,features="lxml")
for link2 in soup2.find_all('a'):
lien2 = link2.get('href')
'''We will now get all href that contains pagecounts in their name. We will have the files based on Time per hour. So 24 hrs is 24 files
and per year is 24*365=8760 files in minimum'''
if "pagecounts" in lien2:
list_of_href_pageviews.append(lohm + lien2)
existing_file_list = []
for file in os.listdir(self.ptsf):
filename = os.fsdecode(file)
existing_file_list.append(filename)
'''Filter the links'''
matching_fnmatch_list = []
if filter_files != '':
for dfilter in download_filter:
fnmatch_list = fnmatch.filter(list_of_href_pageviews, dfilter)
i = 0
for fnl in fnmatch_list:
'''Break for demo purpose only'''
if self.limit_record != 0:
if (i == self.limit_record) and (i != 0):
break
i += 1
matching_fnmatch_list.append(fnl)
'''If the user stated a filter, we will try to remove the files which are outside that filter in the list'''
to_remove = []
for efl in existing_file_list:
for mloh in matching_fnmatch_list:
if efl in mloh:
to_remove.append(mloh)
'''Lets remove the files which has been found outside the filter'''
for tr in to_remove:
matching_fnmatch_list.remove(tr)
matching_fnmatch_list.sort()
'''Multi Threading of 200'''
p = ThreadPool(200)
p.map(self.multithread_download_files_func, matching_fnmatch_list)
except Exception as e:
print('funct download_files' + str(e))
From the accepted answer, I understood that it is simply replacing from multiprocessing import Pool by from multiprocessing.dummy import Pool.
This worked for me.

Im trying to write to a file in a loop but it just seems to be writing nothing?

Here is the full code, it is for a basic random alphabetical shift encryption. For some reason, the .write() don't seem to be working.
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'wt')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
Here is the first .write(). This one is inside a loop.
encrypted_file.write(letter)
y = y + 1
This is the second .write(). This is a single use one
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
The mode key "wt" doesn't exist.
check here! for all proper mode keys
UPDATE: try this
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'a')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
encrypted_file.write(letter)
y = y + 1
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
if you want to overwrite the file use "w" for the mode key

python 2.7 thread not running correctly

I have been fighting with a threaded send of an string image over python sockets for a while now and have had no luck on this issue.
code for the client side is:
import socket
from PIL import ImageGrab #windows only screenshot
from threading import Thread
import win32api, win32con
import re
import win32com.client
import getpass
import time
import select
shell = win32com.client.Dispatch("WScript.Shell")
host = raw_input("SERVER:")
dm = win32api.EnumDisplaySettings(None, 0)
dm.PelsHeight = 800
dm.PelsWidth = 600
win32api.ChangeDisplaySettings(dm, 0)
port = 9000
def picture():
while 1:
image = ImageGrab.grab().resize((800,600)) #send screen as string
data = image.tostring()
sendme = (data)
try:
s.sendall(sendme)
print ("sent")
except socket.error as e:
print e
except Exception as e:
print e
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
pict = Thread(target=picture)
pict.start()
while 1:
socket_list = [s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
data = sock.recv(1024)
print data
if "LEFTC" in data:
data = data.replace("LEFTC","")
x = re.findall(r'X(.*?)Y',data)
y = re.findall(r'Y(.*?)EOC',data)
x = str(x)
y = str(y)
#REPLACE CODE TO BE REWRITTEN
x = x.replace("[","").replace("]","").replace("'","").replace(" ","")
y = y.replace("[","").replace("]","").replace("'","").replace(" ","")
print(str(x) + ' X\n')
print(str(y) + ' Y\n')
try:
win32api.SetCursorPos((int(x),int(y))) #click time
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,int(x),int(y),0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,int(x),int(y),0,0)
except Exception as e:
print e
elif "RIGHTC" in data:
data = data.replace("RIGHTC","")
x = re.findall(r'X(.*?)Y',data)
y = re.findall(r'Y(.*?)EOC',data)
x = str(x)
y = str(y)
#REPLACE FUNCTION MAREKD FOR REWRITE
x = x.replace("[","").replace("]","").replace("'","").replace(" ","")
y = y.replace("[","").replace("]","").replace("'","").replace(" ","")
print(str(x) + ' X\n')
print(str(y) + ' Y\n')
try: #click
win32api.SetCursorPos((int(x),int(y)))
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,int(x),int(y),0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,int(x),int(y),0,0)
except Exception as e:
print e
else:
#This does not work correctly: only BACKSPACE and the else are working.
if "CAPS" in data:
shell.SendKeys('{CAPSLOCK}')
elif "CAPSOFF" in data:
shell.SendKeys('{CAPSLOCK}')
elif "BACKSPACE" in data:
shell.SendKeys('{BACKSPACE}')
elif "SHIFT" in data:
shell.SendKeys('+' + data)
else:
shell.SendKeys(data)
time.sleep(0.1)
server code is:
import socket
import pygame
from pygame.locals import *
from threading import Thread
x = y = 0
host = ""
#port defined here
port = 9000
#This list is used to make the library more pythonic and compact. This also leads to less source code.
keylist = [pygame.K_a,pygame.K_b,pygame.K_c,pygame.K_d,pygame.K_e,pygame.K_f,pygame.K_g,pygame.K_h,pygame.K_i,pygame.K_j,pygame.K_k,pygame.K_l,pygame.K_m,pygame.K_n,pygame.K_o,pygame.K_p,pygame.K_q,pygame.K_r,pygame.K_s,pygame.K_t,pygame.K_u,pygame.K_v,pygame.K_w,pygame.K_x,pygame.K_y,pygame.K_z]
key = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i/o function
def ioinput(sock):
while 1:
evt = pygame.event.poll() #has to be in the same while loop as the evt called or wont work.
if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 1: # one for left
x, y = evt.pos
command = ("LEFTC" + " " + "X" + str(x) + "Y" + str(y) + "EOC")
sock.sendall(command)
elif evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 3: # 3 for right 2 is middle which support comes for later.
x, y = evt.pos
command = ("RIGHTC" + " " + "X" + str(x) + "Y" + str(y) + "EOC")
sock.sendall(command)
elif evt.type == pygame.KEYDOWN:
keyname = pygame.key.name(evt.key)
if evt.key == pygame.K_BACKSPACE:
command = ("BACKSPACE")
sock.sendall(command)
elif evt.key in keylist:
if keyname in key:
command = (keyname)
sock.sendall(command)
def mainloop():
message = []
while 1:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
screen = pygame.display.set_mode((800,600))
clickctrl = Thread(target=ioinput, args=(conn,))
clickctrl.start()
while 1:
d = conn.recv(1024*1024*1)
if not d:
break
else:
message.append(d)
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
except Exception as e:
continue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((host, port))
server.listen(55000)
print "Listening on %s" % ("%s:%s" % server.getsockname())
Main event loop.
mainloop()
The picture thread will run 3 to six times then die however the keyboard and mouse input layer continues to operate. I suspect that the GIL is getting in my way. Am i correct or am I missing something really simple here? This program is supposed to be a simplistic reverse remote desktop appication.
I found the problem after speaking with a good friend. turns out that my server side while loop was setup so that it would break.
i fixed this by changing:
while 1:
d = conn.recv(1024*1024*1)
if not d:
break
else:
message.append(d)
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
to :
while 1:
d = conn.recv(1024*1024*1)
message.append(d)
try:
print("attempting to parse..")
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
print("recieved pic")
except Exception as e:
print e
continue
Also, client side on the picture thread i added a time.sleep (1) after the exception handling, otherwise the image does not come though correctly.

Resources