Here is a code. I doesn't have any skills of tkinter using and duuno how to do output input and saving in tkinter. Prog is working but in console mode. If smb knows how to fix it I will be grateful.
def add(self):
name = input("Имя: ")
addr = input("Адрес: ")
self.__records[name] = addr
messagebox.showinfo('Информация', 'Адрес успешно добавлен!')
def delete(self):
name = input("Имя: ")
if self.__records.get(name) == None:
messagebox.showinfo('Информация', 'Такого человека не существет!')
return
del self.__records[name]
messagebox.showinfo('Информация', 'Адрес успешно удален!')
def dump(self):
for name, addr in self.__records.items():
print('[Имя и адрес] \'%s\': \'%s\'' % (name, addr))
def modify(self):
name = input("Имя: ")
if self.__records.get(name) == None:
messagebox.showinfo('Информация', 'Такого человека не существет!')
return
addr = input("Адрес: ")
self.__records[name] = addr
messagebox.showinfo('Информация', 'Адрес успешно изменен!')
def find(self):
name = input("Имя: ")
if self.__records.get(name) == None:
messagebox.showinfo('Информация', 'Такого человека не существет!')
return
print(self.__records[name])
if len(argv) - 1 == 1:
ab = AddressBook(argv[1])
else:
ab = AddressBook()
I need to move these functions to tkinter so that there is input not in the console, in tkinter
Related
sorry if this is not presented well. This is my first time ever using StackOverflow. I'm trying to create this to keep track of inventory. I do not know how to utilize try-excepts. Additionally, I don't know what else is going wrong. Thanks for any and all help !
data handler:
import os
class DataHandler():
def __init__(self, filename, datadict = {}):
self.filename = filename
self.datadict = datadict
def readData(self): # returns dictionary
try:
fileobj = open(self.filename,'r')
datastr = fileobj.read()
fileobj.close()
# return dictionary read from file or null dictionary
if datastr != '':
return eval(datastr)
else:
return self.datadict
except FileNotFoundError:
return self.datadict # null dictionary
def writeData(self, datadict): # must pass dictionary
fileobj = open(self.filename,'w')
fileobj.write(str(datadict))
fileobj.close()
separate file:
import DataHandler as DH
def menuDisplay():
print("="*40)
print("1 - Add inventory item")
print("2 - Modify inventory item")
print("3 - Delete inventory item")
print("4 - Print inventory list")
print("5 - Exit program")
print("="*40)
selection = input("\nPlease enter menu choice: ")
if selection < "1" and selection > "5":
input("Invalid selection, please enter 1 - 5")
menuDisplay()
else:
return int(selection)
def addItem(invDict,dh):
itemdesc = input("Item Description: ")
itemqty = int(input("Qty: "))
if len(invDict) > 0:
nextKey = sorted(invDict.keys())[-1]+1
else:
nextKey = 1
invDict[nextKey]=[itemdesc,itemqty]
dh.writeData(invDict)
def printInv(invDict):
print("{:<10}{:20}{:6}".format("Item #", "Description", "Qty",))
for dkey, lvalue in invDict.items():
print("{:<10}{:20}{:6d}".format(str(dkey), lvalue[0],lvalue[1], lvalue[2]))
def delItem(invDict,dh):
itemnum = input("Please enter item to delete: ")
del invDict[int(itemnum)]
dh.writeData(invDict)
# complete error checking
def modItem(invDict,dh):
itemnum = input("Please enter item to modify: ")
newqty = input("Please enter the new quantity: ")
invDict[int(itemnum)][1] = int(newqty)
dh = DH.DataHandler("inventory.txt")
invDict = dh.readData()
selection = 0
while selection != 5:
selection = menuDisplay()
if selection == 1:
addItem(invDict,dh)
elif selection == 2:
modItem(invDict,dh)
elif selection == 3:
delItem(invDict,dh)
elif selection == 4:
printInv(invDict)
Updated selenium script with opensource autoliker, i will post social network, username and password because it hard to understan what happens real life, edited some code scrolls still same result only first post liked.
only thing i want is to click like button on
a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
and keep scroling, each like button has same atribute
social network hiall.app
username -whatl0ol
password - tornike123
trying to update source, will post results
source code
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
class FacebookBot:
def __init__(self,username,password,status_report=False):
self.username = username
self.password = password
self.status_report = status_report
options = Options()
options.add_argument("--disable-notifications")
if self.status_report: print("Opening chromedriver...")
self.wd = webdriver.Chrome(chrome_options=options)
if self.status_report: print("Logging in...")
self.login()
def login(self):
self.wd.get("https://hiall.app")
self.wd.find_element_by_name("username").send_keys(self.username)
self.wd.find_element_by_name("password").send_keys(self.password)
self.wd.find_element_by_css_selector("button.btn.btn-main").click()
def convert_to_int(self,string):
try:
return int(string)
except ValueError:
if string.lower().endswith("k"):
string = string[:-2]
try:
return int(float(string)*1000)
except ValueError:
return int(string)*1000
def get_posts(self):
articles = self.wd.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item")
data = []
for a in articles:
if a.get_attribute("id").startswith("span#like-button.btn.btn-default.stat-item"):
likeIts = [i.get_attribute("aria-label").split() for i in a.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item") if i.get_attribute("aria-label")]
likes = {"Like":0,"Love":0,"Haha":0,"Wow":0,"Sad":0,"Angry":0}
likes.update({i[1]: self.convert_to_int(i[0]) for i in likeIts})
try:
button = a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
except exceptions.NoSuchElementException:
continue
data.append({"likes":likes,"button":button,"article":a})
return data
def scroll(self,page_end=100):
find_elem = None
scroll_from = 0
scroll_limit = self.wd.execute_script("return document.body.scrollHeight")
i = 0
while not find_elem:
self.wd.execute_script("window.scrollTo(%d, %d);" % (scroll_from, scroll_from + scroll_limit))
scroll_from += scroll_limit
i += 1
if page_end and i >= page_end:
break
try:
find_elem = self.wd.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
find_elem.click()
except exceptions.ElementNotVisibleException:
find_elem = None
except exceptions.NoSuchElementException:
find_elem = None
def automate(self,unlike=False,page_end=100):
if self.status_report: print("Forcing Facebook to load the posts...")
self.scroll(page_end)
if self.status_report: print("Scrolled down %s times" % page_end)
if self.status_report: print("%s posts..." % ("Unliking" if unlike else "Liking"))
self.wd.execute_script("window.scrollTo(0,0);")
posts = self.get_posts()
num = 0
for p in posts:
if p["likes"]["Angry"] == 0 and p["likes"]["Sad"] == 0 and p["likes"]["Like"] >= 5:
article = p["article"]
self.wd.execute_script("arguments[0].scrollIntoView();", article)
button = article.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
if true:
#button.get_attribute("aria-pressed") == ("true" if unlike else "false"):
num += 1
self.wd.execute_script("arguments[0].click();",button)
try:
p = article.find_element_by_tag_name("p").get_attribute("innerText")
p = p.replace("\n"," ").encode().decode("utf-8")
except exceptions.NoSuchElementException:
p = ""
except:
p = ""
if self.status_report: print(' - %s "%s"' % ("Unliked" if unlike else "Liked",p))
if self.status_report: print("%s %s posts" % ("Unliked" if unlike else "Liked",num))
def close(self):
self.wd.close()
username = "whatl0ol"
password = "tornike123"
pages = False
while pages is False:
inp = input("How many pages to go through? (default 100, 'all' for whole News Feed): ")
if inp.isdigit():
pages = int(inp)
elif inp == "all":
pages = None
unlike = None
while unlike is None:
inp = input("Do you want to Like (l) or Unlike (u) posts? ")
if inp == "l":
unlike = False
elif inp == "u":
unlike = True
bot = FacebookBot(username,password,status_report=True)
bot.automate(unlike=unlike, page_end=pages)
print("Finished")
print()
input("Return to exit")
try:
bot.close()
except:
pass
I'm running windows 10, python 2.7 using pycharm
I'm doing as an exercise a socket chat room, and I've stumbled on a certain problem:
While running the client and server socket from multiple cmd windows,
When I exit one cmd window abruptly, the server is supposed to forward a message to the remaining client - informing them that a client left (including the client's nick)
For some reason it proves to be a problem, the server seems to retain that client in the client list, raising an error as if I sent him that message (which obviously is problematic, because he is no longer there).
When I tried to fix that - changing the loop to not send the message to that specific client (by saving his socket object) -it doesn't send any message.
As if it doesn't recognize the other clients.
My code:
Server:
import socket
import select
import datetime
server_socket=socket.socket()
server_socket.bind(('127.0.0.1',23))
server_socket.listen(5)
open_client_sockets = []
messages_to_send = []
chat_clients={}
def send_waiting_messages(wlist):
for message in messages_to_send:
(sender,msg)=message
if(msg=='\r'):
continue
elif(msg=='quit'):
pass
else:
nick_len=int(msg[:2])
nick=msg[2:2+nick_len]
chat=msg[2+nick_len:]
chat_clients[sender]=nick
for client in wlist:
if(msg=='quit'):
client.send(('{:02d}:{:02d} {} has left the chat!'.format(datetime.datetime.now().hour,datetime.datetime.now().minute,sender)))
else:
if(client is sender):
client.send('NL')
else:
client.send('{:02d}:{:02d} {}: {}'.format(datetime.datetime.now().hour,datetime.datetime.now().minute,nick,chat))
messages_to_send.remove(message)
while True:
rlist,wlist,xlist=select.select([server_socket] + open_client_sockets,open_client_sockets,[])
for current_socket in rlist:
print wlist
if(current_socket is server_socket):
(new_socket,address)=server_socket.accept()
open_client_sockets.append(new_socket)
chat_clients[new_socket]=''
else:
try:
msg=current_socket.recv(1024)
except socket.error as e:
if e.errno==10054:
msg=''
else:
raise
if(msg=='' or msg=='quit'):
if(msg=='quit'):
messages_to_send.append((chat_clients[current_socket], 'quit'))
current_socket.send('quit')
open_client_sockets.remove(current_socket)
del chat_clients[current_socket]
else:
print '{:02d}:{:02d} {} has left the chat!'.format(datetime.datetime.now().hour,
datetime.datetime.now().minute, chat_clients[current_socket])
messages_to_send.append((current_socket, 'quit'))
else:
print msg
messages_to_send.append((current_socket,msg))
send_waiting_messages(wlist)
Client:
import socket
import select
import datetime
server_socket=socket.socket()
server_socket.bind(('127.0.0.1',23))
server_socket.listen(5)
open_client_sockets = []
messages_to_send = []
chat_clients={}
def send_waiting_messages(wlist):
for message in messages_to_send:
(sender,msg)=message
if(msg=='\r'):
continue
elif(msg=='quit'):
pass
else:
nick_len=int(msg[:2])
nick=msg[2:2+nick_len]
chat=msg[2+nick_len:]
chat_clients[sender]=nick
for client in wlist:
if(msg=='quit'):
client.send(('{:02d}:{:02d} {} has left the chat!'.format(datetime.datetime.now().hour,datetime.datetime.now().minute,sender)))
else:
if(client is sender):
client.send('NL')
else:
client.send('{:02d}:{:02d} {}: {}'.format(datetime.datetime.now().hour,datetime.datetime.now().minute,nick,chat))
messages_to_send.remove(message)
while True:
rlist,wlist,xlist=select.select([server_socket] + open_client_sockets,open_client_sockets,[])
for current_socket in rlist:
print wlist
if(current_socket is server_socket):
(new_socket,address)=server_socket.accept()
open_client_sockets.append(new_socket)
chat_clients[new_socket]=''
else:
try:
msg=current_socket.recv(1024)
except socket.error as e:
if e.errno==10054:
msg=''
else:
raise
if(msg=='' or msg=='quit'):
if(msg=='quit'):
messages_to_send.append((chat_clients[current_socket], 'quit'))
current_socket.send('quit')
open_client_sockets.remove(current_socket)
del chat_clients[current_socket]
else:
print '{:02d}:{:02d} {} has left the chat!'.format(datetime.datetime.now().hour,
datetime.datetime.now().minute, chat_clients[current_socket])
messages_to_send.append((current_socket, 'quit'))
else:
print msg
messages_to_send.append((current_socket,msg))
send_waiting_messages(wlist)
Help would be much appreciated!
I have also been trying trying to make a chat room and I have been successful. You might want to look at my code to find the solution.
Server
import threading
from queue import Queue
import socket
host = ''
port = 5000
client_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1000)
def conn():
while True:
(host, port) = s.accept()
f = len(client_list)
client_list.append(host)
print(client_list)
p1 = threading.Thread(target=clientam, args=str(f))
p2 = threading.Thread(target=threader)
p2.start()
p1.start()
p1.join()
p2.join()
def clientam(client):
size = 3000
client = int(client)
c = client_list[client]
print(c)
c.send("Welcome to the chatroom".encode())
while True:
try:
data = c.recv(size).decode()
if data == "exit":
for l in client_list:
if l == c:
pass
else:
l.send("The other person has left the chatroom".encode())
client_list[client] = ''
print(client_list)
c.close()
break
else:
for l in client_list:
if l == c:
pass
else:
l.send(data.encode())
except Exception:
for l in client_list:
if l == c:
continue
else:
try:
l.send("The other person has left the chatroom".encode())
except Exception:
pass
break
try:
c.close()
except Exception:
break
def threader():
t = threading.Thread(target=conn)
t.start()
t.join()
threader()
client
import socket
import threading
import time
import pickle
host = '127.0.0.1'
port = 5000
s = socket.socket()
d = 0
print_lock = threading.Lock()
def conn():
global d
global s
try:
if d == 1:
s = socket.socket()
s.connect((host, port))
d = 0
elif d == 0:
s.connect((host, port))
except Exception:
conn()
def reciever():
global d
global g
g = False
li = [128, 3, 88, 0, 113, 46]
size = 3000
while True:
try:
data = s.recv(size).decode()
data = str(data)
with open('Data.txt', 'a') as f:
f.write(data)
if str(data) == 'The other person has left the chatroom':
with print_lock:
print(data)
elif str(data) == "Welcome to the chatroom":
g = True
with print_lock:
print(str(data))
else:
try:
int(data)
continue
except Exception:
with print_lock:
print("Other Person:> " + str(data))
except Exception as e:
with print_lock:
print("You have been disconnected")
d = 1
s.close()
with print_lock:
print('Trying to connect to server')
conn()
def sender():
global d
global g
while True:
if g == True:
while True:
with print_lock:
i = input('You:> ')
if i == 'exit':
try:
s.send(i.encode())
with print_lock:
print("You have been disconnected")
d = 1
except Exception:
with print_lock:
print('You have been disconnected')
d = 1
elif i == "connect":
if d == 0:
with print_lock:
print("Server already connected")
elif d == 1:
with print_lock:
print('Server connecting')
conn()
else:
try:
if d == 0:
s.send(i.encode())
elif d == 1:
with print_lock:
print('Server is disconnected')
except Exception:
with print_lock:
print('Server is disconnected')
def threader():
p1 = threading.Thread(target = reciever)
p1.start()
p2 = threading.Thread(target = sender)
p2.start()
p1.join()
p2.join()
conn()
threader()
I'm doing creating a address book for a computer science class, where we are supposed to have a list of objects "contact" written to a file when the program closes and read from the file when the program starts. However, after the data is written to the file, once it is read it does not seem to keep its object form.
import pickle
class Contact:
#Creating the class with the attributes I want
def __init__(self, firstname, lastname, number, areacode, city):
self.firstname = firstname
self.lastname = lastname
self.number = number
self.areacode = areacode
self.city = city
def __str__(self):
return "({0} {1}, {2}, {3}, {4})".format(self.firstname, self.lastname, self.number, self.areacode, self.city)
#reading the object
def opendata():
readable = []
addresses = []
A = open("Address_book", "rb+")
addresses = A.read()
A.close
B = len(addresses)
if B != 0:
readable = pickle.loads(addresses)
return readable
else:
return addresses
def savedata(file):
addresses = open("Address_book", "wb+")
temp = pickle.dumps(file)
addresses.write(temp)
addresses.close()
def Address_manager():
Address = []
fromfile = opendata()
Address.append(fromfile)
while True:
print("add = add contact, modify = modify contact, search = search contacts, end = close program, print = print full list")
A = input("What do you want to do?: ")
if A == "end":
savedata(Address)
break
else:
if A == "print":
for i in Address:
print(str(i))
print("")
continue
elif A == "add":
Address.append(add_contact())
print("")
continue
elif A == "search":
lists2 = search_contact(Address)
A = 0
for i in lists2:
A += 1
print(A, str(i))
print("")
print("")
continue
elif A == "modify":
modified = modify_contact(Address)
Address.append(modified)
print("")
continue
def add_contact():
while True:
try:
A = Contact(input("First name: "), input("Last name: "), input("Phone Number: "), input("Area Code: "), input("City: "))
print(str(A))
B = input("Is this right?: (y/n)")
if B == "y":
print("Well done?")
return A
else:
print("Try Again")
continue
except:
print("bad data")
If I try to "print" the list after getting it from the file it prints them in the wrong form. What am I doing wrong and why?
Edit 1: I apologize for the less than efficient code.
Edit 2: Added function to add contact
What's the best way to implement this - reuse user input on menu?
Here's my sample code below:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1():
user, passwd, vcenter = input()
do something
def function2():
user, passwd, vcenter = input()
do something
def function3():
user, passwd, vcenter = input()
do something
def main():
while True:
if choice == 1:
function1()
elif choice == 2:
function2()
elif choice == 3:
function3()
else:
print 'Choose from the options only!'
break
I think i get what you mean, you want to use the input() once in the while loop, and not repeat calling it in every function. if so I suggest this solution:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1(param):
user, passwd = param
do something
def function2(param):
user, passwd = param
do something
def function3(param):
user, passwd = param
do something
def main():
while True:
if choice in [1,2,3]:
param = input()
if choice == 1:
function1(param)
elif choice == 2:
function2(param)
elif choice == 3:
function3(param)
else:
print 'Choose from the options only (1, 2, 3): '
break
hope this helps.