I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.
Related
So I made a very simple Auto-typer and want to be able to run it again or quit it.
All works perfectly fine but at the end the "ending = input()" doesnt let me type it just exits out of the programm. Any reason why?
import pyautogui
import time
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
break_loop = 1
while break_loop <= 1:
secs_inbetween_actions = float(input("""
Seconds between actions(should be float but int is also ok): """))
no_of_lines = int(input("""
How many Lines do you want to write?(Only int): """))
time_between_action = int(input("""
How long should the time between enter and writing be?: """))
lines = ""
print("""
Write your Text under this message (You have """ + str(no_of_lines) + """ line(s) to wite)
""")
for i in range(no_of_lines):
lines += input() + "\n"
print("-------------------------------------")
while time_between_action > 0:
time_between_action = time_between_action - 1
print('Time Left until writing -+==> ' + str(time_between_action))
time.sleep(1)
print("-------------------------------------")
pyautogui.typewrite(lines, interval=secs_inbetween_actions)
ending = input("If you want to use this aplication once again type 'y' + 'enter key' ,if not press the 'enter key': ")
if ending == "y":
break_loop = 1
clearConsole()
else:
break_loop += 1
This is a rather fun little problem. It occurs, as #Barmar notes, because pyautogui.typewrite() is writing to the console for you. I incorrectly thought that it was not happening when there was no delay between actions, which was a far more puzzling little problem.
In this case the solution is easy: add after your typewrite():
if lines:
input()
To absorb what has just been typed for you.
I'm trying to make sure the input the user uses is all letters.I tried the .alpha method but since this is a file, a "." will be included returning it false. I also tried using "quit" sentinel value to exit the program but that isn't working. It keeps saying break is outside the loop. I also want the user to keep inputting if the file is not found error is raised.
The Assignment1
def main():
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
counter = 0
for line in FiletoReadFrom:
outputFile = open("output.txt", "a+")
counter = counter + 1
outputFile.write("/* {} */ {}\n".format(counter, line.strip()))
if counter == 0:
print("This is an empty file")
else:
print("The file has been made")
FiletoReadFrom.close()
outputFile.close()
def inputTxt():
flag = True
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == quit:
flag == False
break
print("goodbye")
else:
return FileName
def openingFile(filetoReadFrom):
try:
a = open(filetoReadFrom, 'r')
return a
except FileNotFoundError:
print("This File was not Found", "Enter again or type quit to exit")
main()
There are different questions here, which is frowned upon on this site. Please never do that again.
the quit and break problem:
It is just a typo. As you forgot quoting 'quit', Python sees it at an undeclared variable which gives a syntax error. Fix:
...
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == 'quit':
flag == False
break
...
But it is still wrong, because break will only exit from the loop and inputTxt will return None which is not what you expect. Calling sys.exit() could be better here.
Test for letters and not numbers:
You must choose a white list (only alphas and dot) or black list (no numbers) way. In idiomatic Python it could be:
if all((x.isalpha() or x == '.') for x in FileName): # white list
# process error condition
if any(x.isdigit() for x in FileName): # black list
# process error condition
You could also use the re module which is great at controlling that a string respect a given pattern...
keep asking until a valid file is given:
You should use a loop:
def main():
while True:
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
if FileToReadFrom is not None: # openingFile returns None when file does not exist
break
But IMHO, you should remove the openingFile function and directly use (and test) open in main
I started learning Python a couple days ago and wanted to create this "responsive program" that did some basic things like showing a calendar or weather. Everything works fine until it says "What can I help you with?" where it only shows the same line again. I am sorry if this is basic I just started Python somedays ago.
Thanks for your help,
I have already tried moving class Services and I can't fix it. Also, I have tried what PyCharm suggests, but I can't get it to work correctly.
#First attempt at responsive code
#Code made by dech
print('Hello! My name is Py. What is your name?')
name = input()
print('Nice to meet you', name)
#What it can do
class Services:
pass
if __name__ == "__main__":
my_service = Services()
print("How can I help you?")
while True:
action = input(
"I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
elif action == 'W':
my_services.weather()
elif action == 'C':
my_services.Calendar()
def createCalendar(entry):
pass
class Services(object):
pass
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
import string
import json
from urllib.request import urlopen
# parameters
params1 = "<||^{tss+^=r]^/\A/+|</`[+^r]`;s.+|+s#r&sA/+|</`y_w"
params2 = ':#%:%!,"'
params3 = "-#%&!&')&:-/$,)+-.!:-::-"
params4 = params2 + params3 # gives k
params_id = "j+^^=.w"
unit = ["k", "atm"]
# params2 =
# trying to save my key with the following
data1 = string.printable
data2 = string.punctuation + string.ascii_uppercase + string.ascii_lowercase + string.digits
encrypt = str.maketrans(dict(zip(data1, data2)))
decrypt = str.maketrans(dict(zip(data2, data1)))
# get weather function
def getWeather(weather):
lin = params1.translate(decrypt)
kim = params4.translate(decrypt)
idm = params_id.translate(decrypt)
# open this
link = urlopen(lin + weather + idm + kim).read()
getjson = json.loads(link)
# result = getjson.gets()
print("Weather result for {}".format(weather), '\n')
"""
get json objects // make'em
"""
main = getjson.get("main", {"temp"}) # temperature
main2 = getjson.get("main", {"pressure"}) # pressure
main3 = getjson.get("main", {"humidity"}) # humidity
main4 = getjson.get("main", {"temp_min"})
main5 = getjson.get("main", {"temp_max"})
wind = getjson.get("wind", {"speed"}) # windspeed
sys = getjson.get("sys", {"country"}) # get country
coord = getjson.get("coord", {"lon"})
coord1 = getjson.get("coord", {"lat"})
weth = getjson.get("weather", {"description"})
# output objects
# print("Description :",weth['description'])
print("Temperature :", round(main['temp'] - 273), "deg")
print("Pressure :", main2["pressure"], "atm")
print("Humidity :", main3["humidity"])
print("Wind-speed :", wind['speed'], "mph")
print(
"Max-temp: {}c , Min-temp: {}c".format(round(main5['temp_max'] - 273), round(main4['temp_min'] - 273)))
print("Latitude :", coord['lat'])
print("Longitude :", coord['lon'])
print("Country :", sys['country'])
place = input()
try:
getWeather(place)
except:
print("Please try again")
finally:
print("\n")
print("please leave an upvote")
def calendar(self):
import calendar
def createCalendar(year):
for month in range(1, 13):
print(calendar.month(year.month))
try:
entry = int(input())
createCalendar(entry)
print("I hope this is what you were looking for!")
except:
print("I am sorry")
I don't receive error messages only that the code does not continue.
You have an infinite loop:
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
# The rest of your code is outside the loop.
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
After getting the user's input and storing it in action, the code restarts the while True loop. Only the codes indented after the while loop are part of the loop.
You should move your code inside the loop.
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
# do stuff
elif action == 'W':
# do stuff
elif action == 'C':
# do stuff
In addition to the infinite loop, you need to fix these other issues:
Learn to indent your code properly and consistently. Indentation is important in Python. The PEP8 standard dictates using 4 spaces. You seem to be using more than 4.
Remove the duplicate, unnecessary class Services: pass codes. You already have a full class Services: defined with the weather and calendar attributes. You don't need to nest it inside another Services class.
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
# your weather code
def calendar(self):
# your calendar code
if __name__ == "__main__":
# main code
my_services.Services()
# use my_services.weather...
# use my_services.calendar...
Be consistent in your variable names. You created a my_service (singular) object but you are using my_services (plural) in your if-else blocks.
Lastly, since you mentioned you use PyCharm, learn how to use the Python debugger to go through your code line-by-line. The debugger is a very helpful tool to check issues with your code.
So far I've been attempting to create a 2 factor authentication script in python. It works very well now and I wanted to create a gui since this will be running nearly 24/7 on a raspberry pi.
TLDR; I don't understand what the docs mean by "stretch. Pass a string describing if rows/columns should stretch, to fill the entire GUI. "
#!/usr/bin/env python
import pyotp
import os
import sys
import math
import time
from appJar import gui
udstart = 1
app = gui("2FA Keys","480x320")
def count(n):
while n >= 0:
time.sleep(1)
n -= 1
if n == 0:
return 1
#Keygenertor function pass the base32 code
def keyGen(secret):
secretcalc = pyotp.TOTP(secret)
code = secretcalc.now()
Lcode = list(code)
Lcode.insert(3, " ")
Ocode = ''.join(Lcode)
return Ocode
#INIT CODES GO HERE
CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL")
SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5")
app.stretch(columns)
app.setFont(50)
app.addLabel("l2", "Sia Coin: " + SiaCoinCode, 0,0,0,0)
app.setLabelbg("l2", "blue")
app.addLabel("l1", "Coinbase: " + CoinbaseCode, 1,0,0,0) #Coinbase 2FA
app.setLabelBg("l1", "red")
while True:
if udstart == 1:
break
else:
time.sleep(30)
break
def update():
#UPDATE CODES GO HERE
CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL") #Coinbase
SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5")
app.setLabel("l2", "Sia Coin: " + SiaCoinCode)
app.setLabelBg("l2", "blue")
app.setLabel("l1", "Coinbase: " + CoinbaseCode)
app.setLabelBg("l1", "red")
#profit???
udstart = 0
app.registerEvent(update)
app.go()
I have no idea what to pass it.
If you look at the appJar source code on GitHub, you can identify what you should pass for stretch:
Looking at how strech is used:
def setStretch(self, exp):
self.setExpand(exp)
...
stretch = property(getStretch, setStretch)
Looking at the source for the setExpand we see the possible values for strech:
def setExpand(self, exp):
if exp.lower() == "none":
self.containerStack[-1]['expand'] = "NONE"
elif exp.lower() == "row":
self.containerStack[-1]['expand'] = "ROW"
elif exp.lower() == "column":
self.containerStack[-1]['expand'] = "COLUMN"
else:
self.containerStack[-1]['expand'] = "ALL"
As a result, the possible strings are (case insensitive) "None", "Row", "Column", or anything else (which will result in "ALL").
It's also documented here: http://appjar.info/pythonWidgetLayout/#set-stretch-sticky
none, row, column, both
I wrote this script for a program I'm writing ever since I changed careers but running into a lot of issues with it. Supposed to take a string and encrypt it with a key. Not sure where to begin with troubleshooting as I'm new to programming so came here for help. Maybe if you can just point me in the write direction where to begin?
This is the error I get but looks fine.
$ python temp.py -p "ThisIsATestOfMyCode" -k "testtest"
File "encrypt.py", line 37
else:
^
This is my code.
#!/usr/bin/env python
import sys, argparse
def encrypt(varAble1, varAble2):
varAble1_size = len(varAble1)/float(len(varAble2))
if str(varAble1_size).split(".")[1] == "0":
else:
while str(varAble1_size).split(".")[1] != "0":
varAble1 +== "#"
varAble1_size = len(varAble1)/float(len(varAble2))
code = []
varAble1 = list(varAble1)
varAble2 = list(varAble2))
multiply_size = int(str((varAble1_size)).spliy(".")[0]) * 8
while varAble1 != []:
p_varAble1 = varAble1[0:8]
p_varAble2 = varAble2[0:8]
temp_list = []
for i in xrange(0,8):
if type(p_varAble2[i]) == type(int):
new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
code.append(new_ct)
temp_list.append(new_ct)
varAble1.pop(0)
p_varAble1.pop(0)
varAble2 = temp_list
varAble2.reverse()
code.reverse()
varAble1 = code.reverse()
code_text = []
for i in code:
hex_value = hex(i)
if len(hex_value) != 4:
code_text.append("0" + hex(i)[2:])
else:
code_text.append(hex(i)[2:])
varAble2 += i
code_text = "".join(code_text).upper()
return code_text
def main():
parser = argparse.ArgumentParser(description="Encrypt things")
parser.add_argument("-p", "--var1",help="String to enc",metavar='<pt>', required=True)
parser.add_argument("-k", "--var2", help="8 length key to encrypt with", metavar='<key>', required=True)
args = parser.parse_args()
var1 = args.var1
var2 = args.var2
hash = encrypt(var1, var2)
print "[+] Encrypted using %s [+]\n%s" % (var2, hash)
if __name__ == "__main__":
main()
The block of if str(varAble1_size).split(".")[1] == "0": is empty, so you will need to add a pass statement after it. Keef Baker is also correct in spotting that the block for else: on line 37 is not properly indented.
You have to indent your code after else :
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
And as Andrew Kulpa noted, the block after
if str(varAble1_size).split(".")[1] == "0":
is empty, so you either need to do something in that block, or add a pass statement.
Python does not use brackets but indentation for control flow.
In your code, the Python interpreter sees an else but no statement for it, so it throws an error.
See more about control flow here : https://docs.python.org/3/tutorial/controlflow.html