I'm working on a Python script using Blessed and can't get the 'hidden_cursor()' function to work properly.
It will successfully hide the cursor but it won't set the visibility back on exit.
This is what I tried so far:
with term.hidden_cursor():
while True:
command = raw_input (term.move(27, 2) + "")
if command == "X":
os.system('clear')
sys.exit()
else:
os.system('clear')
main('self')
And here's the full script: https://gist.github.com/lovemac15/c5e71e0b8aa428693e5b
Thanks! :D
Try changing the control flow to be sure to exit the with block:
with term.hidden_cursor():
while True:
command = raw_input (term.move(27, 2) + "")
if command == "X":
os.system('clear')
sys.exit()
else:
os.system('clear')
break
main('self')
Related
I tried making a while loop, however, I can't break it. I am new to programming and maybe I am bitting more than I can chew, but I would be grateful if someone could help me. I am using pywhatkit and I have a problem defining the searching variable.
import pywhatkit as pwt
def searching_mode():
searching = (input(''))
while True:
print(f"Searching ...")
if searching == pwt.search(input('')):
continue
else:
searching == (input('exit'))
break
searching_mode()
Your input should be in while loop so it can continue execute the input when there's no input or break when the input is 'exit'. Try this:
import pywhatkit as pwt
def searching_mode():
while True:
searching = input('Search for? (type "exit" to exit) : ')
if 'exit' in searching:
break
elif not searching:
continue
else:
print(f'Searching for "{searching}"...')
pwt.search(searching)
searching_mode()
Output:
Search for? (type "exit" to exit) : python course
Searching for "python course"...
Search for? (type "exit" to exit) :
Search for? (type "exit" to exit) : stackoverflow python while loop
Searching for "stackoverflow python while loop"...
Search for? (type "exit" to exit) : exit
Process finished with exit code 0
Hi if you can give more information about what you want to achiev and give full script can help better. But you can try setting up a switch to break a loop for example;
def searching_mode():
switch = True:
searching = (input(''))
while switch:
print(f"Searching ...")
if searching == pwt.search(input('')):
continue
else:
searching == (input('exit'))
switch = False
searching_mode()
While loop will continue to run if you construct like "while True", so you can setup a condition to break from it. by using
while switch:
if condition1:
#do something:
else:
#do this
switch = False
# so next time it
Why is the input() after the if statement not working?
I need some help, the input() after the if statement is supposed to stop the script, however it just continues. If i give it another command, for example print("...") or time.sleep(10) it will execute, it is only the input() that does not work. Any ideas?
Edit: Because it might not be clear what the intention is. When asking for an input after the if statement the script should wait before continuing. This is because I want it to pause after I move the mouse so that it does not keep spamming the keys, but I am able to resume it if needed.
import time
from pynput.keyboard import Key, Controller as KeyController
from pynput.mouse import Controller as MouseController
key = KeyController()
mouse = MouseController()
def f1_toggle():
key.press(Key.f1)
key.release(Key.f1)
def enter_toggle():
key.press(Key.enter)
key.release(Key.enter)
input("Press any key to start:")
time.sleep(5)
while True:
start_position = mouse.position
key.press(Key.ctrl_l)
print("Ctrl pressed")
f1_toggle()
print("F1 toggled")
key.release(Key.ctrl_l)
print("Ctrl released")
time.sleep(1)
enter_toggle()
print("Enter toggled")
time.sleep(.5)
end_position = mouse.position
if start_position != end_position:
input("Press any key to continue ")
You're calling enter_toggle() before you ask for input. This is simulating pressing the Enter key. This is being used as the response to the input() call, so it doesn't wait for the user to enter something manually.
Are you sure the two variables are different?
I don't have pyinput, and I am using python 3.8, but in my computer, the input isn't skipped (I commented the pyinput).
Try this:
try:
input("Press any key to continue ")
except Exception as e:
print(e);
Try to see if this helps and what it prints.
I want to make a system in python what was listen to keypresses and when I hit enter something happens depends on the value of the command I write.
How can I do this?
I try to write this:
import keyboard
def run_buffer(cmd):
print("\nThe buffer value is: {}, The buffer size is: {}".format(cmd, len(cmd)), end="")
buffer = ""
def on_press(e):
global buffer
if e.name == "enter": # When I hit enter I need to run the 'command' and emtpy the buffer.
run_buffer(buffer)
buffer = ""
elif e.name == "backspace":
buffer = buffer[0:-1]
elif e.name == "f4":
print("Asd")
elif len(e.name) == 1:
buffer += e.name
keyboard.on_press(on_press)
while True: # This was just for the script has runtime and won't stop immediately.
a = 0
When I run the script sometimes works perfectly, but sometimes it's just too late and the cursor not follow my expectations.
I get this in the console
I hope someone can help me :D
Thanks for help, and sorry for my bad English.
I made a program that asks you at the end for a restart.
I import os and used os.execl(sys.executable, sys.executable, * sys.argv)
but nothing happened, why?
Here's the code:
restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
print("\nThe program will be closed...")
sys.exit(0)
import os
import sys
restart = input("\nDo you want to restart the program? [y/n] > ")
if restart == "y":
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
print("\nThe program will be closed...")
sys.exit(0)
os.execl(path, arg0, arg1, ...)
sys.executable: python executeable
os.path.abspath(__file__): the python code file you are running.
*sys.argv: remaining argument
It will execute the program again like python XX.py arg1 arg2.
Maybe os.execv will work but why not use directly using os.system('python "filename.py"') if you have environment and path variable set something like :
import os
print("Hello World!")
result=input("\nDo you want to restart the program? [y/n] > ")
if result=='y':
os.system('python "C:/Users/Desktop/PYTHON BEST/Hackerrank.py"')
else:
print("\nThe program will be closed...")
try using;
while True:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
break
or
retry = True
while retry:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
retry = False
It is a way that you can easily modify to your liking, and it also means that you can load variables once instead of loading them every time you restart. This is just a way to do it without any libraries. You indent all your code and put it in a while loop, and that while loop determines whether your code restarts or not. To exit it, you put in a break or change a variable. It is easiest because you don't have to understand a new library.
Just import the program you want to restart and run it under the desired condition like this
Title: hello. py
import hello
if (enter generic condition here):
hello
os.execv(sys.executable, ['python'] + sys.argv)
solved the problem.
I am trying to detect global keypresses in python. (I am a complete noob in Python). My problem is that pyHook recognizes my key events but it doesn't let me type anymore. If I try to type something into the opened selenium webdriver (see code), nothing happens, except for the keyid being printed.
Here is my code:
import pyHook, pythoncom, sys, win32api
from colorama import Fore, init
from selenium import webdriver
add_key = 187 #keyID for "+" key
commands = ["start", "quit", "save", "help"]
urls = []
driver = webdriver.Chrome()
def OnKeyboardEvent(event):
print(event.KeyID)
if event.KeyID == add_key:
print("add key pressed")
urls.append(driver.current_url)
return 0
def PrintHelpMessage():
# write help message
MainLoop()
def MainLoop():
print(Fore.GREEN + "type commands for more help.")
usr_input = input()
if usr_input == "commands":
print(Fore.GREEN + "available commands: start, quit, save, help")
command_input = input()
if command_input in commands:
if command_input == "start":
hook_manager = pyHook.HookManager()
hook_manager.KeyDown = OnKeyboardEvent
hook_manager.HookKeyboard()
pythoncom.PumpMessages()
elif command_input == "quit":
sys.exit(0)
elif command_input == "save":
# implement save function
print("Save function implemented soon")
elif command_input == "help":
PrintHelpMessage()
init(autoreset = True) # init colorama -> makes it possible to use colored text in terminal
print(Fore.RED + "---easy playlist manager---")
driver.get("http://youtube.com")
MainLoop()
Maybe someone can tell me how to fix it?
greetings
You're are returning 0 in OnKeyboardEvent, so the keyboard event is not passed to other handlers or the window itself. If you don't want to filter the event, you should return True.
See Event Filtering in the documentation for more information.