I am creating a chat room application using a CLI over a GUI, and I am on windows so I just use the default terminal in command prompt to run my code. My program detects individual key presses and then adds them to a list in my data class, which, when joined, creates the user's message. The only problem I'm having here is that the program records keypresses even when it is not in focus. Is there any way I can detect if the terminal is in focus or not so I can handle keypresses appropriately? What I have here at the moment is essentially an accidental keylogger of sorts.
My code (although not useful to the question I feel I should add it just in case):
import json, keyboard, os, socket, termcolor, threading
def addKey(key):
data.line.append(key)
data.lineLength += 1
def cls():
os.system("cls")
def display_chatLog():
return "\n".join(data.chatLog)
def display_lineLength():
return f"Characters: {data.lineLength}/{data.maxLineLength}\n\n"
def display_userInput():
return f"\n{data.start} {''.join(data.line)}{data.end}\n"
def enterPressed():
joinLine = " ".join(data.line)
if data.server:
if data.lineLength <= data.maxLineLength:
data.server.send(bytes(f"{data.username}: {joinLine}", "utf-8"))
data.line = []
else:
data.warning = "Your message is too long"
else:
if data.line[0] == "host":
port = data.line[1]
else:
IP = data.line[1]
port = data.line[2]
def getKeys():
specialKeys = ("backspace", "ctrl", "enter", "esc", "shift", "right shift", "space")
while True:
key = keyboard.read_event()
keyType = key.event_type
keyName = key.name
if keyType == "down":
if keyName not in specialKeys:
addKey(keyName)
elif keyName == "backspace":
if len(data.line) > 0:
del data.line[len(data.line) - 1]
data.lineLength -= 1
elif keyName == "enter":
enterPressed()
elif keyName == "shift":
if keyboard.is_pressed(f"shift+{keyName}") and keyName not in specialKeys:
addKey(keyName.upper)
elif keyName == "space":
addKey(" ")
class data:
chatLog = []
end = "_"
line = []
lineLength = 0
maxLineLength = 512
server = None
start = ">>>"
warning = "Make sure to either host a server using 'host (port)' or join one by using 'join (IP adress) (port)'"
getKeys_thread = threading.Thread(target = getKeys)
getKeys_thread.start()
while True:
cls()
print(display_chatLog(), display_userInput(), display_lineLength(), "\n", termcolor.colored(data.warning, "red", "on_white"))
import ctypes
def getWindow():
hwnd = ctypes.windll.user32.GetForegroundWindow()
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
return (buff.value, hwnd) # buff.value is the title of the window, hwnd is the window handle
This code which I got from here and edited slightly allows me to capture the name and window handle of the currently focused window.
Related
I'm trying to use a python script to make a connection with my 4x4 keypad on Rastberry (RPi.GPIO).
The code does not work correctly, because the first and second rows does not respond. I'm trying to use pad4pi, but in my case, this not work.
This is the code I'm using in the moment.
(Main Control)
import RPi.GPIO as GPIO
import time
import serial
import Keypad
#import Open_CV
ROWS = 4 # number of rows of the Keypad
COLS = 4 #number of columns of the Keypad
keys = [ '1','2','3','A', #key code
'4','5','6','B',
'7','8','9','C',
'*','0','#','D' ]
rowsPins = [18,22,29,31] #connect to the row pinouts of the keypad
colsPins = [32,33,36,37] #connect to the column pinouts of the keypad
# the pins need to be these, because the others are already in use
# Configure the use of the serial terminal and the baud rate
ser = serial.Serial( #"/dev/ttyS0", 9600)
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
#ConfiguraĆ§Ć£o inicial dos terminais GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# call the video method
#video("teste.mp4")
def loop():
keypad = Keypad.Keypad(keys,rowsPins,colsPins,ROWS,COLS) #create Keypad object
keypad.setDebounceTime(50) #set the debounce time
# call the video method
#video('/home/pi/share/teste.mp4')
while(True):
key = keypad.getKey() #obtain the state of keys
if(key != keypad.NULL): #if there is key pressed, print its key code.
print ("You Pressed Key : %c "%(key))
ser.write(str.encode(key))
time.sleep(1)
#ret, frame = cap.read()
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#cv2.imshow('frame',gray)
#if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#cap.release()
#cv2.destroyAllWindows()
if __name__ == '__main__': #Program start from here
print ("Program is starting ... ")
try:
loop()
except KeyboardInterrupt: #When 'Ctrl+C' is pressed, exit the program.
GPIO.cleanup()
(keypad functions)
#!/usr/bin/env python3
########################################################################
# Filename : Keypad.py
# Description : The module of matrix keypad
# Author : freenove
# modification: 2016/07/13
########################################################################
import RPi.GPIO as GPIO
import time
#class Key:Define some of the properties of Key
class Key(object):
NO_KEY = '\0'
#Defines the four states of Key
IDLE = 0
PRESSED = 1
HOLD = 2
RELEASED = 3
#define OPEN and CLOSED
OPEN = 0
CLOSED =1
#constructor
def __init__(self):
self.kchar = self.NO_KEY
self.kstate = self.IDLE
self.kcode = -1
self.stateChanged = False
class Keypad(object):
NULL = '\0'
LIST_MAX = 10 #Max number of keys on the active list.
MAPSIZE = 10 #MAPSIZE is the number of rows (times 16 columns)
bitMap = [0]*MAPSIZE
key = [Key()]*LIST_MAX
holdTime = 500 #key hold time
holdTimer = 0
startTime = 0
#Allows custom keymap, pin configuration, and keypad sizes.
def __init__(self,usrKeyMap,row_Pins,col_Pins,num_Rows,num_Cols):
GPIO.setmode(GPIO.BOARD)
self.rowPins = row_Pins
self.colPins = col_Pins
self.numRows = num_Rows
self.numCols = num_Cols
self.keymap = usrKeyMap
self.setDebounceTime(10)
#Returns a single key only. Retained for backwards compatibility.
def getKey(self):
single_key = True
if(self.getKeys() and self.key[0].stateChanged and (self.key[0].kstate == self.key[0].PRESSED)):
return self.key[0].kchar
single_key = False
return self.key[0].NO_KEY
#Populate the key list.
def getKeys(self):
keyActivity = False
#Limit how often the keypad is scanned.
if((time.time() - self.startTime) > self.debounceTime*0.001):
self.scanKeys()
keyActivity = self.updateList()
self.startTime = time.time()
return keyActivity
#Hardware scan ,the result store in bitMap
def scanKeys(self):
#Re-intialize the row pins. Allows sharing these pins with other hardware.
for pin_r in self.rowPins:
GPIO.setup(pin_r,GPIO.IN,pull_up_down = GPIO.PUD_UP)
#bitMap stores ALL the keys that are being pressed.
for pin_c in self.colPins:
GPIO.setup(pin_c,GPIO.OUT)
GPIO.output(pin_c,GPIO.LOW)
for r in self.rowPins: #keypress is active low so invert to high.
self.bitMap[self.rowPins.index(r)] = self.bitWrite(self.bitMap[self.rowPins.index(r)],self.colPins.index(pin_c),not GPIO.input(r))
#Set pin to high impedance input. Effectively ends column pulse.
GPIO.output(pin_c,GPIO.HIGH)
GPIO.setup(pin_c,GPIO.IN)
#Manage the list without rearranging the keys. Returns true if any keys on the list changed state.
def updateList(self):
anyActivity = False
kk = Key()
#Delete any IDLE keys
for i in range(self.LIST_MAX):
if(self.key[i].kstate == kk.IDLE):
self.key[i].kchar = kk.NO_KEY
self.key[i].kcode = -1
self.key[i].stateChanged = False
# Add new keys to empty slots in the key list.
for r in range(self.numRows):
for c in range(self.numCols):
button = self.bitRead(self.bitMap[r],c)
keyChar = self.keymap[r * self.numCols +c]
keyCode = r * self.numCols +c
idx = self.findInList(keyCode)
#Key is already on the list so set its next state.
if(idx > -1):
self.nextKeyState(idx,button)
#Key is NOT on the list so add it.
if((idx == -1) and button):
for i in range(self.LIST_MAX):
if(self.key[i].kchar == kk.NO_KEY): #Find an empty slot or don't add key to list.
self.key[i].kchar = keyChar
self.key[i].kcode = keyCode
self.key[i].kstate = kk.IDLE #Keys NOT on the list have an initial state of IDLE.
self.nextKeyState(i,button)
break #Don't fill all the empty slots with the same key.
#Report if the user changed the state of any key.
for i in range(self.LIST_MAX):
if(self.key[i].stateChanged):
anyActivity = True
return anyActivity
#This function is a state machine but is also used for debouncing the keys.
def nextKeyState(self,idx, button):
self.key[idx].stateChanged = False
kk = Key()
if(self.key[idx].kstate == kk.IDLE):
if(button == kk.CLOSED):
self.transitionTo(idx,kk.PRESSED)
self.holdTimer = time.time() #Get ready for next HOLD state.
elif(self.key[idx].kstate == kk.PRESSED):
if((time.time() - self.holdTimer) > self.holdTime*0.001): #Waiting for a key HOLD...
self.transitionTo(idx,kk.HOLD)
elif(button == kk.OPEN): # or for a key to be RELEASED.
self.transitionTo(idx,kk.RELEASED)
elif(self.key[idx].kstate == kk.HOLD):
if(button == kk.OPEN):
self.transitionTo(idx,kk.RELEASED)
elif(self.key[idx].kstate == kk.RELEASED):
self.transitionTo(idx,kk.IDLE)
def transitionTo(self,idx,nextState):
self.key[idx].kstate = nextState
self.key[idx].stateChanged = True
#Search by code for a key in the list of active keys.
#Returns -1 if not found or the index into the list of active keys.
def findInList(self,keyCode):
for i in range(self.LIST_MAX):
if(self.key[i].kcode == keyCode):
return i
return -1
#set Debounce Time, The defaul29t is 50ms
def setDebounceTime(self,ms):
self.debounceTime = ms
#set HoldTime,The default is 500ms
def setHoldTime(self,ms):
self.holdTime = ms
#
def isPressed(self, keyChar):
for i in range(self.LIST_MAX):
if(self.key[i].kchar == keyChar):
if(self.key[i].kstate == self.self.key[i].PRESSED and self.key[i].stateChanged):
return True
return False
#
def waitForKey(self):
kk = Key()
waitKey = kk.NO_KEY
while(waitKey == kk.NO_KEY):
waitKey = self.getKey()
return waitKey
def getState(self):
return self.key[0].kstate
#
def keyStateChanged(self):
return self.key[0].stateChanged
def bitWrite(self,x,n,b):
if(b):
x |= (1<<n)
else:
x &=(~(1<<n))
return x
def bitRead(self,x,n):
if((x>>n)&1 == 1):
return True
else:
return False
I'm writing a Jukebox program that plays media based on key combinations (A1, B2, C3, etc.). Everything works the way I expect with the exception of the "media_player.next()" command.
Let's say you queue up 3 songs. If you hit the "y" key, it skips the song as I'd expect. My issue is that once it gets to the 3rd song, if you hit "y" again, it will circle back to the first song. I don't want that. I want the "y" key to take you forward in the media list...if that is the last song in the media list, don't go to the next song. How do I know if that's the last song in the media list or how do you stop VLC from going back to the beginning?
#!/usr/bin/env python3
#
import os, sys, csv, vlc, time, serial
from pynput.keyboard import Key, Listener
#
# Set Defaults
#
DefaultUSBPath="/media/pi"
#
# Declare variables
#
USBDrive = None
Action = None
Playlist = []
SelectionCount = []
Sel_char = None
#
# Find the USB Drive
#
USBDrive = os.path.join(DefaultUSBPath, "USB30FD")
#
# Adding to playlist - Returns directory contents and adds to playlist
#
def addplaylist(track):
list = None
if os.path.isdir(os.path.join(USBDrive, track)):
files = [f for f in os.listdir(os.path.join(USBDrive, track)) if os.path.isfile(os.path.join(USBDrive, track, f))]
for f in files:
if list is None:
list = os.path.join(USBDrive, track, f)
else:
list = list + ";" + os.path.join(USBDrive, track, f)
else:
print ("Error(3) - Selection is invalid")
if list is None:
print ("Error(4) - Selection has no media")
return list
#
# MediaPlayer function
#
def vlc_WhatsPlaying():
pass
def vlc_SongStarted(event):
print("Started")
song = media_player.get_media_player().get_media().get_mrl() # return path of current playing media
print(song)
splittrack = song.split("/")
track = splittrack[-2]
print(track)
return
def vlc_SongFinished(event):
print("Finished")
song = media_player.get_media_player().get_media().get_mrl() # return path of current playing media
print(song)
splittrack = song.split("/")
track = splittrack[-2]
#media_list.remove_index(0)
#media_player.play_item_at_index(1)
return
#
# Define keyboard actions
#
def on_press(key):
global Action, player
try:
Sel_char = int(key.char)
except:
try:
Sel_char = str(key.char)
Sel_char = Sel_char.upper()
except:
Sel_char = None
if Sel_char == "Z":
return False
elif Sel_char == "Y":
print("Skip")
media_player.next()
elif type(Sel_char) == str:
Action = Sel_char
elif type(Sel_char) == int:
Plist = None
Action = Action + str(Sel_char)
print("Action: " + Action)
Plist = addplaylist(Action)
if Plist is not None:
if ";" in Plist:
print(Plist)
Plist = Plist.split(";")
for p in Plist:
media_list.add_media(p)
else:
media_list.add_media(Plist)
# find section in array and increase the count by one
if not media_player.is_playing():
media_player.play()
else:
print ("Error(4) - Selection has no media")
else:
pass
#
# Setting Up Media Player
#
# creating Instance class object
player = vlc.Instance('--no-xlib --quiet ') # no-xlib for linux and quiet don't complain
media_player = vlc.MediaListPlayer() # creating a media player object
media_list = player.media_list_new() # creating a new media list
media_player.set_media_list(media_list) # setting media list to the media player
new = player.media_player_new() # new media player instance
media_player.set_media_player(new) # setting media player to it
media_events = new.event_manager() # setting event handler
# setting up events
media_events.event_attach(vlc.EventType.MediaPlayerMediaChanged, vlc_SongStarted)
media_events.event_attach(vlc.EventType.MediaPlayerEndReached, vlc_SongFinished)
# Read keyboard input
#
print("Ready...")
with Listener(on_press=on_press) as listener:
listener.join()
#
# Program is shutting down
#
print ("")
print ("Have a nice day!")
print ("")
sys.exit()
As mentioned in my comment the MediaListEndReached doesn't appear to do anything for me, so running with the idea of the list being the easiest way of addressing the issue, the following code tests the list position of the item being played and exits, if the next or previous command attempts to pass beyond the end of the list.
You can achieve the same result simply tracking an index variable.
You may have to adjust the splitting of the mrl to match the entries in your list.
import vlc
import time
## pinched from vlc for keyboard input
import termios
import tty
import sys
mymedia = ["vp.mp3","vp1.mp3","happy.mp3"]
def getch(): # getchar(), getc(stdin) #PYCHOK flake
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch
## end pinched code
def jukebox():
player.play_item_at_index(0)
m = player.get_media_player()
print("Playing - ",m.get_media().get_mrl())
while True:
k = getch()
if k == "n": #Next
media = m.get_media()
if media.get_mrl().rsplit("/",1)[1] == mymedia[-1]: #Next requested but already at the end
break
player.next()
if k == "p": #Previous
media = m.get_media()
if media.get_mrl().rsplit("/",1)[1] == mymedia[0]: #Previous requested but already at the beginning
break
player.previous()
if k == " ": #Pause
player.pause()
if k == "q": #Quit
player.stop()
return True
time.sleep(0.1)
state = player.get_state()
print(state,m.get_media().get_mrl())
print("End of list")
vlc_instance = vlc.Instance('--no-xlib --quiet ') # no-xlib for linux and quiet don't complain
player = vlc_instance.media_list_player_new()
Media = vlc_instance.media_list_new(mymedia)
player.set_media_list(Media)
print("Welcome to Jukebox")
print("Options - space = Play/Pause, n = Next, p = Previous, q = Quit")
print("Media",mymedia)
jukebox()
i am creating a telegram bot using python and i can't update the global variable in the callback function please help
i have tried to updated the variable using global FLAG inside a callback function but the variable is still the same
FLAG = 0
def start_all(bot,update):
global FLAG
chat_id = update.message.chat_id
FLAG = 0
sell = telegram.KeyboardButton(text="buy")
buy = telegram.KeyboardButton(text="sell")
custom_keyboard =[[ sell, buy ]]
reply_markup = telegram.ReplyKeyboardMarkup(
custom_keyboard)
bot.send_message(chat_id=chat_id,
text="Thank you",
reply_markup=reply_markup
)
command= update.effective_message.text
if command == "buy":
buy = Buy()
FLAG = 1
buy.start(bot,update)
elif command == "sell":
sell = Sell()
FLAG = 2
sell.start(bot,update)
else:
#help
pass
def main():
updater = Updater('')
dp = updater.dispatcher
dp.add_handler(CommandHandler('test',test))
dp.add_handler(CommandHandler('start',start_all))
if FLAG == 1:
buy = Buy()
dp.add_handler(MessageHandler(Filters.location,
buy.start))
elif FLAG == 2:
sell = Sell()
dp.add_handler(MessageHandler(Filters.location, sell.insert_user_to_database))
elif FLAG == 0:
dp.add_handler(MessageHandler(Filters.text, start_all))
else:
pass
i expected the FLAG will be 1 when i click buy ,2 when i click sell and check if i clicked buy or sell in main function and handle the filters accordingly
I am pretty sure that the IF statement is incorrect here. Telegram update.message.text is not a string so the evaluation will always fail and go to pass.
Try changing it to:
command = str(update.message.text)
Edit:
Additionally it seems to me you should be using a query-structure like this:
def start(update, context):
keyboard = [[InlineKeyboardButton("BUY", callback_data='buy'),
InlineKeyboardButton("SELL", callback_data='sell')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('WANT TO BUY OR SELL?', reply_markup=reply_markup)
updater.dispatcher.add_handler(CommandHandler('start', start))
def flag(update, context):
query = update.callback_query
command = str(update.callback_query.data)
if command == 'buy':
FLAG = 1
#do stuff
elif command == 'sell':
FLAG = 2
#do stuff
else:
pass
updater.dispatcher.add_handler(CallbackQueryHandler(flag))
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.
So i have this code here in python 3.3, it cyphers text with the ceaser cypher.
What i need to know is how do i make a script that will convert it back from the original so that the person i send it too can read it.
message = input("Input: ")
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
print ("Output: " + coded_message)
One more thing, I plan to be putting this is a tkinter message box, with the two entry fields used for the input and output. one field should be used to type what i want to convert and the other should be used to show what the text looks like after it has been crypted. The button should start the encryption. here is the code:
import sys
from tkinter import *
def mHello():
mLabel = Label(mGui,text = input("Hello World"))
mLabel.grid(row=3, column=0,)
mGui = Tk()
ment = StringVar()
mGui.geometry("450x450+250+250")
mGui.title("My TKinter")
# input label
mLabel = Label(mGui,text = "Input",)
mLabel.grid(row=1,column=0,)
# output label
mLabeltwo = Label(mGui,text = "Input",)
mLabeltwo.grid(row=2,column=0,)
# convert button
mButton = Button(text = "Convert",command = mHello)
mButton.grid(row=3,column=0)
# input entry
mEntry = Entry(mGui,textvariable=ment)
mEntry.grid(row=1,column=1)
# output entry
mEntryTwo = Entry(mGui,textvariable=ment)
mEntryTwo.grid(row=2,column=1)
mGui.mainloop()
By the way i am only 15 and this is my 2nd day learning python.
Some credit goes to sources on this forum that have provided me with some code snippets
Thank-you in advance guys!
Before i say anything else you should be aware that minds much greater the mine have advised against writing your own cypher script for anything other then learning
If you want them to be able to decode your code then provide them with a key. so in your case:
s maps to h
t maps to i
f maps to t
I hope this code illustrates my suggestion:
In [1]: from cyro import your_cyrptic_function
In [2]: key = {'s':'h', 't':'i', 'f':'t'}
In [3]: secret_word = your_cyrptic_function('hit')
In [4]: decyrpted_secret_word = ''
In [5]: for letter in secret_word:
decyrpted_secret_word += key[letter]
...:
In [6]: print(decyrpted_secret_word)
hit
For the code above i turned your original code into a function:
def your_cyrptic_function(secret):
message = secret
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
return coded_message
there are several great ways to do this in python. If your interested in cyptopgraphy then check out Udacities class cs387 applied cryptography