This is a program related to windows operations. I have made different versions of this program. So I tried writing a version using classes. I am a beginner and thought this will help me understand the concept but I am getting some errors like
Method 'shutdown_windows' may be 'static'
There are many errors like this and I would like to get some insight about them and how to solve them
This is my code:
import os
import datetime
import time
class WindowsOperations(object):
def __init__(self, shutdown, restart, open_app, close_app):
self.shutdown = shutdown
self.restart = restart
self.open_app = open_app
self.close_app = close_app
def shutdown_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute: #
os.system("shutdown /s /t 1")
break
def restart_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("shutdown /r /t 1")
break
def open_application(self):
app_name_open = input("Enter the application name you want to open: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.startfile(app_name_open)
break
def close_application(self):
app_name_close = input("Enter the application name you want to close: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("TASKKILL /F /IM " + app_name_close)
break
choice = int(input("Enter your choice \n1.Shutdown Windows \n2.Restart Windows "
"\n3.Open an application \n4.Close an application \n:"))
time_hour = int(input("Enter hour: "))
time_minutes = int(input("Enter minutes: "))
time_now = datetime.datetime.now()
remaining_time = ((time_minutes - time_now.minute) * 60 + (time_hour - time_now.hour) * 3600) % 86400
print(remaining_time)
my_windows_operation = WindowsOperations('shutdown', 'restart', 'open_app', 'close_app')
if choice == 1:
my_windows_operation.shutdown_windows()
elif choice == 2:
my_windows_operation.restart_windows()
elif choice == 3:
my_windows_operation.open_application()
elif choice == 4:
my_windows_operation.close_application()
else:
print("Please enter a valid input")
Please do modify the code if necessary and give me some tips
The second "Parameter 'shutdown' unfilled" is an error. It's coming because you've defined WindowsOperations intitializer to take 4 parameters:
def __init__(self, shutdown, restart, open_app, close_app):
But when actually creating the object you are passing noothing:
my_windows_operation = WindowsOperations()
You definitely need to fix that.
The first "Method 'shutdown_windows' may be 'static'" is more of a suggestion. It's coming because the method shutdown_windows does not use self - i.e. it need not be part of the class to do it's job.
Related
I'm currently learning how to code with python, and I thought the best way would be learning by doing so I tried to create a voice assistant but it just stops working after a few iterations.
The code below isn't very efficient nor clean, but it works except for the part that it stops after a few iterations of listening.
there are no error mesages nor does the code actually stop it just doesn't do anything
thank you for every suggestion in advance
import speech_recognition as sr
import pyttsx3
import datetime as dt
# import wikipedia
# import webbrowser
import os
# import time
# import subprocess
# import ecapture as ec
# import wolframalpha
# import json
# import requests
# from gtts import gTTS
import random as ran
from docx import Document
document = Document()
note_new = ""
note_complete = ""
adding_more = True
second = dt.datetime.now().second
minute = dt.datetime.now().minute
hour = dt.datetime.now().hour
hour_str = str(hour)
minute_str = str(minute)
second_str = str(second)
time = hour_str + ":" + minute_str + ":" + second_str + " "
# initialising the text to speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
# <editor-fold desc="Listening to the Users input">
# listening to the Users input
statement = ""
def listen():
global statement
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
statement = r.recognize_google(audio, language='en-in')
except Exception as e:
# speak("Pardon me, please say that again")
return "None"
return statement
# </editor-fold>
# <editor-fold desc="Talking">
def talk(text):
engine.say(text)
engine.runAndWait()
# </editor-fold>
# <editor-fold desc="Key Words">
# KeyWord Functions
def hello():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Hello Sir, welcome home.")
talk("Hello Sir, welcome home.")
elif random_text == 2:
print("Hello, welcome home.")
talk("Hello, welcome home.")
elif random_text == 3:
print("Welcome back.")
talk("Welcome back.")
def minecraft():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Minecraft...")
talk("Initialising Minecraft")
elif random_text == 2:
print("Minecraft coming right up...")
talk("Minecraft coming right up")
elif random_text == 3:
print("Starting Minecraft")
talk("Starting Minecraft")
os.startfile("C:\Spiele\Minecraft\MinecraftLauncher.exe")
def chrome():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Chrome...")
talk("Initialising Chrome")
elif random_text == 2:
print("Chrome coming right up...")
talk("Chrome coming right up")
elif random_text == 3:
print("Starting Chrome...")
talk("Starting Chrome")
os.startfile("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
def valorant():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Valorant...")
talk("Initialising Valorant")
elif random_text == 2:
print("Valorant coming right up...")
talk("Valorant coming right up")
elif random_text == 3:
print("Starting Valorant...")
talk("Starting Valorant")
os.startfile("C:/Spiele/Riot Games/VALORANT/live/VALORANT.exe")
def aim_lab():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Aim Lab...")
talk("Initialising Aim Lab")
elif random_text == 2:
print("Aim Lab coming right up...")
talk("Aim Lab coming right up")
elif random_text == 3:
print("Starting Aim Lab...")
talk("Starting Aim Lab")
os.startfile("steam://rungameid/714010")
def clock():
global second
global minute
global hour
global hour_str
global minute_str
global second_str
global time
second = dt.datetime.now().second
minute = dt.datetime.now().minute
hour = dt.datetime.now().hour
hour_str = str(hour)
minute_str = str(minute)
second_str = str(second)
time = hour_str + ":" + minute_str + ":" + second_str + " "
print("It's " + hour_str + " hours and " + minute_str + " minutes")
talk("It's " + hour_str + " hours and " + minute_str + " minutes")
def note():
global adding_more
global note_new
global note_complete
print("How should i call the note?")
talk("How should i call the note?")
listen()
note_name = statement
while adding_more:
print("Ok you can start talking:")
talk("Ok you can start talking:")
listen()
note_new = statement
print("new: " + note_new)
note_complete = note_complete + " " + note_new
print("new: " + note_complete)
print("Do you want to add more?")
talk("Do you want to add more?")
listen()
if "yes" in statement.lower():
adding_more = True
if "no" in statement.lower():
adding_more = False
print("printing...")
talk("printing..")
note_name_txt = note_name + ".txt"
note_name_complete = note_name_txt
f = open(note_name_complete, "w+")
f.write(note_complete)
f.close()
print("ready")
talk("ready")
print("should i open the note?")
talk("should i open the note?")
listen()
if "yes" in statement.lower():
note_name_complete = str(note_name_complete)
note_name_path = note_name_complete.replace(" ", "_")
os.startfile("D:/Python/Projekts/Jarvis/" + note_name_complete)
def dice():
number = 6
print("What sould be the range")
talk("What sould be the range")
listen()
try:
number = int(statement)
except:
print("I could not understand you sorry Sir!")
dice()
random_number = ran.randint(1, number)
print("The D " + str(number) + " says " + str(random_number))
talk("The D" + str(number) + "says" + str(random_number))
def stop():
global hour
if hour <= 12:
print("have a good day!")
talk("have a good day!")
if 19 >= hour < 12:
print("Goodbye")
talk("bye")
if hour > 19:
print("Goodnight!")
talk("Goodnight")
quit()
# </editor-fold>
if __name__ == '__main__':
while True:
statement = " "
listen()
print(statement)
command = statement.lower()
if "jarvis" in command:
if "hello" in command:
hello()
if "minecraft" in command:
minecraft()
if "chrome" in command:
chrome()
if "valorant" in command:
valorant()
if "time" in command or "clock" in command:
clock()
if "note" in command:
note()
if "dice" in command:
dice()
if "aim" in command or "lab" in command:
aim_lab()
if "stop" in command or "bye" in command or "goodbye" in command or "goodnight" in command:
stop()
If you report:
stops working after a few iterations
Then I would look for the loop (where iterations happen usually). I found the only obvious loop in the main block:
Shorten the loops
if __name__ == '__main__':
while True:
statement = '' # initialize as empty string
listen()
print(statement)
execute_command(statement.lower())
Extracted your command switch into a method execute_command:
def execute_command(command):
if "jarvis" in command:
if "hello" in command:
hello()
if "minecraft" in command:
minecraft()
if "chrome" in command:
chrome()
if "valorant" in command:
valorant()
if "time" in command or "clock" in command:
clock()
if "note" in command:
note()
if "dice" in command:
dice()
if "aim" in command or "lab" in command:
aim_lab()
if "stop" in command or "bye" in command or "goodbye" in command or "goodnight" in command:
stop()
Then watch out to the understood command that is printed.
Which command was the last printed before the loop stopped?
Design pure functions (returning a value)
This goes hand in hand with another common programming advice:
Don't use global variables!
def listen():
statement = '' # remove global, make it local and return
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
statement = r.recognize_google(audio, language='en-in')
except Exception as e:
# speak("Pardon me, please say that again")
return "None"
return statement # you had the return already; use it!
Then your main (and other usage locations) would change to:
if __name__ == '__main__':
while True:
statement = listen() # use the return
print(statement)
execute_command(statement.lower())
Sometimes it works fine, sometimes throws an error. Cannot figure it out. No matter how many inputs.
Thats the error. Is it the order of the code or something else?
give_gift.remove(reciever)
ValueError: list.remove(x): x not in list
Code:
import random
import os
import time
random.seed()
buy_gift = []
give_gift = []
names = True
print('Add name, then press ENTER. To finish type "end".')
while names is True:
name = input()
if name == "end":
if len(buy_gift) < 2:
print("Go play with your own gift. Goodbye!")
print()
os.system("PAUSE")
quit()
else:
names = False
else:
buy_gift.append(name)
give_gift.append(name)
exchange = len(give_gift)
os.system("cls")
time.sleep(1)
print("Drawing pairs...")
print()
time.sleep(1)
while exchange > 0:
giver = random.choice(buy_gift)
reciever = random.choice(give_gift)
while giver == reciever:
reciever = random.choice(buy_gift)
print(giver,"buys gift for",reciever)
time.sleep(0.25)
buy_gift.remove(giver)
give_gift.remove(reciever)
exchange -= 1
print()
os.system("PAUSE")
There is an issue with this line:
while giver == reciever:
reciever = random.choice(buy_gift)
It should be:
reciever = random.choice(give_gift)
import time
listy = ['timer','stopwatch']
def intro():
print("This is a program which contains useful tools")
print(listy)
def timer():
x = int(input("How long Seconds ?"))
while x > 0:
print(x)
time.sleep(1)
x -= 1
def stopwatch():
verif = input("Do you want to start y/n \n")
if verif == 'y':
x = 0
while True:
print(x, end = "\b"*5)
time.sleep(1)
x += 1
def main():
intro()
decider = input("Which Program?")
if decider.lower() == 'timer':
timer()
elif decider.lower() == 'stopwatch':
stopwatch()
main()
in this code i dont know why the \b escape sequence isnt working in cmd or in idle, can anyone explain why? Is it because of a logic error?
A flush may be required. How about...
print("{0}{1}".format("\b"*5, x), end="", flush=True)
I need help for my python assignment. We have to make a quiz program and I am having trouble with restarting a function.
I need something like continue, but instead runs the function again. Also, some tips on returning values from functions cant hurt! Thanks! ~Also, I just started using python 2 weeks ago, so this is pretty advanced to me. EDIT: Thanks to user: 2ps! :D
#Quiz YAY!
#
#Name Removed
#
#Version 1.0
#
score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode");
print("Opening Overide Console")
cmd = input("Enter Command call exit{} to exit: ")
if cmd == "corr":
print("Adding one point")
score=score+1
return(score);
elif cmd== "manScoreChng":
score=int(input("What do want the score to be?"));
elif cmd == 'stop{}':
raise Exception('Quit by User')
score = modMode(score);
print(score);
To capture the return of the modMode function, just make sure you return something at the end:
score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode")
print("Opening Overide Console")
cmd = input("Enter Command: ")
if cmd == "corr":
print("Adding one point")
score = score+1
elif cmd == "manScoreChng":
score = int(input("What do want the score to be?"))
elif cmd == 'exit':
raise Exception('Bye!')
return int(score) # MAKE SURE YOU HAVE THIS LINE HERE
To call the modScore command over and over again, use a loop.
try:
while True:
score = modMode(score) # grab the returned value from modMode by using `=`
print(score)
except Exception:
pass
This will run until the user types in exit.
I've made this little alarm clock with a little help from my brother. I tried it last night, with out the nonBlockingRawInput and that worked fine, but with the nonBlockingRawInput it didn't work. Today I've tried it but neither of them work! I will post the code with the nonBlockingRawInput and the "non" file. If you want the code without nonBlockingRawInput, just ask.
Thanks in advance.
alarm rpi.py:
import time
import os
from non import nonBlockingRawInput
name = input("Enter your name.")
print("Hello, " + name)
alarm_HH = input("Enter the hour you want to wake up at")
alarm_MM = input("Enter the minute you want to wake up at")
print("You want to wake up at " + alarm_HH + ":" + alarm_MM)
while True:
now = time.localtime()
if now.tm_hour == int(alarm_HH) and now.tm_min == int(alarm_MM):
print("ALARM NOW!")
os.popen("open mpg321 /home/pi/voltage.mp3")
break
else:
print("no alarm")
timeout = 60 - now.tm_sec
if nonBlockingRawInput('', timeout) == 'stop':
break
non.py:
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = input(prompt)
signal.alarm(0)
return text
except AlarmException:
pass
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''
I've been looking at your code for a while now. As far as I can understand you want to be able to run an alarm while also being able to type "stop" in the shell to end the program, to this end you can make the alarm a thread. The thread will check if its time to say "ALARM!" and open the mp3. If the user hasn't typed stop in the shell, the thread will sleep and check again later.
I essentially used your code and just put it into an alarm thread class:
import time
import os
import threading
class Alarm(threading.Thread):
def __init__(self, hours, minutes):
super(Alarm, self).__init__()
self.hours = int(hours)
self.minutes = int(minutes)
self.keep_running = True
def run(self):
try:
while self.keep_running:
now = time.localtime()
if (now.tm_hour == self.hours and now.tm_min == self.minutes):
print("ALARM NOW!")
os.popen("voltage.mp3")
return
time.sleep(60)
except:
return
def just_die(self):
self.keep_running = False
name = raw_input("Enter your name: ")
print("Hello, " + name)
alarm_HH = input("Enter the hour you want to wake up at: ")
alarm_MM = input("Enter the minute you want to wake up at: ")
print("You want to wake up at: {0:02}:{1:02}").format(alarm_HH, alarm_MM)
alarm = Alarm(alarm_HH, alarm_MM)
alarm.start()
try:
while True:
text = str(raw_input())
if text == "stop":
alarm.just_die()
break
except:
print("Yikes lets get out of here")
alarm.just_die()
It is worth noting, that when the thread is sleeping, with:
time.sleep(60)
And you typed stop in the shell the thread would have to wake up before it realised it was dead, so you could at worst end up waiting a minute for the program to close!
import winsound,time
a= int(input("Enter how many times I have beep :"))
b= int(input("Enter when to wake up (in seconds) :"))
time.sleep(b)
for i in range(a):
winsound.Beep(3000,100)
winsound.Beep(2500,100)
winsound.Beep(2000,100)
winsound.Beep(1000,100)
winsound.Beep(500,100)