Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I currently have a Twitter bot that streams tweets from Twitter in my timeline. Regardless of what it does, how could I also send Tweets (get keyboard input) at the same time as receiving Tweets (looping code).
This isn't a question about the Twitter API, just a general question on how to get input while looping code.
I'd create a specific thread for it, when used would call your Twitter API post function. (But it depends how your code is structured)
import threading
t1 = threading.Thread(target=post_from_keyboard)
t1.start()
t1.join()
# Loop exits when users writes quit.
# Obviously it won't post any Tweets with the word "quit"
def post_from_keyboard():
while(True):
kb_tweet = input("Enter Tweet or write "quit" to exit")
if kb_tweet != "quit"
your_tweet_api_call( kb_tweet )
else:
break
I understand that you don't want your loop to wait for you to enter a tweet in each iteration, so you can't use the most common method raw_input.
In this case, it is platform specific. For Unix systems, you should use the select module, while in Windows, you have the msvcrt one.
With select, the idea is to check stdin inside every iteration, and process the message when you get one.
Something like:
import sys
import select
while True:
message = select.select([sys.stdin], [], [], timeout=0.1)[0]
if message:
print(message)
Perhaps,you are looking for something like this
userInput = raw_input()
while(userInput != q):
#do something
userInput = raw_input()
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want python to be printing a bunch of numbers like 1 to 10000. Then I want to decide when to stop the numbers from printing and the last number printed will be my number. something like.
for item in range(10000):
print (item)
number = input("")
But the problem is that it waits for me to place the input and then continues the loop. I want it to be looping until I say so.
I'll appreciate your help. Thanks.
Catch KeyboardInterrupt exception when you interrupts the code by Ctrl+C:
import time
try:
for item in range(10000):
print(item)
time.sleep(1)
except KeyboardInterrupt:
print(f'Last item: {item}')
You can use the keyboard module:
import keyboard # using module keyboard
i=0
while i<10000: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
print(i)
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('Last number: ',i)
break # finishing the loop
else:
i+=1
except Exception:
break
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is my first question, as I have started to code recently.
here it goes...
I dont know how to do it, so I haven't coded it yet.
The idea is to have a Conditional to try doing something for x seconds, and if nothing happens on this x seconds, then do something to try it again.
Like this..
Try for 5 seconds to:
click on element to download something # <- this I know how to do
if nothing happens: # <- no error, just not executed the line above
refresh the page
try again:
finally:
You have your file
sorry for my English, as it is not my primary language and I am also learning it...
what web scraping tool you are using? selenium ? I can only give you my
logic if you do not post your code.
import datetime
def page_refresh():
print('refresh page')
driver.refresh()
def check_and_wait():
status_ready = False
while (not status_ready):
start_time = datetime.now()
while(not status_ready and datetime.now()-start_time<5): # loop 5 seconds
if(condtion == True): # if something happen
status_ready = True
return
page_refresh() # nothing happen , loop again
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using notepad++ for writing codes and then seeing output using Windows Power Shell. Now lets say I want to print this...
"Stack Overflow"
But not all at once. First of all it will print S then t then a then c then k then a space and then O ...... ?
So is there any function/method to post the text as we type in old PCs?
If the question is not complete let me know what more information I can provide you.
Update
#uʍop ǝpısdn Yes, you understood my requirement. And many thanks for the answer. :)
Well I didn't know that it calls Emulating text. :)
Here you go:
import time, sys
for letter in "Stack Overflow":
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(1) # that's in seconds, adjust at will
sys.stdout.write('\n')
Why stdout.flush?
Output from a running program is usually buffered (i.e. held waiting) until certain conditions are met. The call to sleep() will not fulfill these conditions, and the text will not appear. By calling flush() after each letter, you force it out.
from __future__ import print_function # only needed for Python 2.x
import random
from time import sleep
def delay_print(s, min_delay=0.1, max_delay=0.8):
for ch in s:
delay = min_delay + random.random() * (max_delay - min_delay)
sleep(delay)
print(ch, end="")
print('')
delay_print("StackOverflow")
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having a problem where I want the user to be able to input text to call functions. It works perfectly fine except for one thing. :/ Once something has been input nothing can be done afterwards. The only way to solve it is run the program again which is not convenient. I have spent a lot of time looking for an answer and need help. I also think other amateurs like me might be wondering this too.
An example of the code:
x = raw_input('test1')
if x == 'x':
print 'test2'
The result:
test1x
test2
x
'x'
As you can see it works once then stops working. For the record I'm using Python 2. Hope this can be solved :)
You need to use a loop if you want to program to keep running.
Here is a simple example:
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
The program will keep running until you type hello
You can use the following function
def call():
input = raw_input('input: ')
if input == 'yes':
print 'yes'
call()
call()
last_data = ''
while last_data != 'yes':
input = raw_input('ENTER SOMETHING: ')
#do whatever you want with input
last_data = raw_input('DO YOU WANT TO QUIT? (yes/no): ')
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm pretty new to Python and would like to write a (not computer) language trainer for my students. Just something like where a timer runs in the background and the student has to input words quickly to slow down/revert the countdown - otherwise the countdown reaches zero and displays some "game over" message. (Just like when a special agent has to defuse a bomb while the timer races towards zero.)
There are tons of explanations of threading which sounds like the right way to do it, sure, but so far I haven't found anything where a timer is combined with a (time-limited) raw_input. Could any of you pros give me a pointer to the tutorial/discussion I have overlooked?
import threading
import time
import os
def ask():
"""
Simple function where you ask him his name, if he answers
you print message and exit
"""
name = raw_input("Tell me your name, you have 5 seconds: ")
exit_message = "Wohoho you did it..Your name is %s" % name
exit(exit_message)
def exit(msg):
"""
Exit function, prints something and then exits using OS
Please note you cannot use sys.exit when threading..
You need to use os._exit instead
"""
print(msg)
os._exit(1)
def close_if_time_pass(seconds):
"""
Threading function, after N seconds print something and exit program
"""
time.sleep(seconds)
exit("Time passed, I still don't know your name..")
def main():
# define close_if_time_pass as a threading function, 5 as an argument
t = threading.Thread(target=close_if_time_pass,args=(5,))
# start threading
t.start()
# ask him his name
ask()
if __name__ == "__main__":
main()
You don't have to do it via threading, you could in a single thread run through your 'logic' at a specific frequency and each iteration recalculate the countdown via a time-delta method. This is how many video games are produced.
Lets say you run this pseudo-code method at 60hz:
delta = timenow-timelast;
countdown -= delta;
if(input)
processInputHere;
You should be able to convert the pseudo-code to python code to make it work