Additional loop when stoping while loop - multithreading

I've created a function using the carriage return from this and threading trick to exit loop from this. The function will keep counting until a keystroke is detected.
Everything works fine except an additional line is printed whenever I kill the loop.
For example in console:
Press anything to stop it: 6 #<------------- pressed enter
Press anything to stop it: 7 #<------------- additional line produced
import _thread
import time
import sys
def input_thread(list):
input()
list.append(None)
def do_stuff():
counter = 0
list = []
_thread.start_new_thread(input_thread,(list,))
while not list:
time.sleep(0.1)
sys.stdout.write("Press anything to stop it: %d \r" % (counter))
sys.stdout.flush()
counter += 1
How can I prevent extra line being printed? I suspect it has something to do with the while loop has to finish additional loop in order to exit. If the answer to this question is too obvious please let me know the keyword to search for.
Thanks a million!

Related

Python 3 - wait for all .exe instances to close before opening more in a loop

I hope that title is clear. Please consider the below:
import subprocess
import time
for i in range(0, 20, 5):
print(i)
time.sleep(3)
process1 = subprocess.Popen(["G:\\mydir\\myfile.exe"])
process1.wait()
time.sleep(3)
process2 = subprocess.Popen(["G:\\mydir\\myfile.exe"])
process2.wait()
time.sleep(3)
process3 = subprocess.Popen(["G:\\mydir\\myfile.exe"])
process3.wait()
...the purpose of this code should be:
1) Increment for 0, 20 by 5.
2) For each pass of the loop, open three instances of an executable that will do some stuff.
3) Once all three have finished executing and closed, complete the next iteration of the loop.
...the idea is that there will never be more than 3 instances open, but always at least 1 during each pass of the loop.
However, with the above code, each of the three processes is waiting for the previous one to end. So there are still three .exe instances per loop, however there is never more than one open at any one time.
What do I need to do so I get the desired behaviour?
Thanks
Instead of waiting for each subprocess directly after creating it, wait for all subprocesses at the end of the loop. Both can be done in a nested loop.
import subprocess
import time
for i in range(0, 20, 5):
print(i)
child_processes = []
# open all subprocesses
for _ in range(3):
time.sleep(3)
child_processes.append(subprocess.Popen(["G:\\mydir\\myfile.exe"]))
# wait on all subprocesses
for child_process in child_processes:
child_process.wait()

How can I make a program that takes 3 seconds and then print in the console

The code below works at first but then I erased and retyped it and it doesn't work anymore. I don't know what is wrong but when I run it it should wait for 2 seconds and print s9 in the console, not print s first and print 9 two seconds later. I don't know what is wrong
I tried to add flush=True but it doesn't work
from time import sleep
print('s', end='')
sleep(2)
print(9)
I expect it will wait 2 seconds and print s9, not print s first and print 9 2 seconds later
Code is read in order. First line is read and executed, then the second, so on and so forth.
First, you import the sleep() method from the time module with from time import sleep.
Then, you print "s" without newline with print('s', end='')
Then you wait 2 seconds with sleep(2)
And finally you print "9" with a newline with print(9).
However, it is not what you want. You want to first wait 2 seconds and then print "s" and "9". To do that, you just have to switch the order:
from time import sleep
sleep(2)
print('s', end='')
print(9)
Even better, you can put the last two lines together :
from time import sleep
sleep(2)
print("s9")
Your Code is running from the top to bottom.
So your part here:
print('s', end='')
sleep(2)
print(9)
First prints "s" then waits 2s and then prints 9. You can either move the first print below the sleep like this:
sleep(2)
print('s', end='')
print(9)
Or, like #rdas suggested, just print once:
from time import sleep
sleep(2)
print('s9')

PyAutoGui while loop interruption

So I have been searching the Internet trying to figure out what I am doing wrong here. Basically, I want to create a script that will prompt the user to enter a number, then perform the ctrl-v paste operation that many times. I have tried variation upon variation of the below, but it is just not working.
The commands work fine outside the loop, but the moment I try to loop it, the program just crashes. I am probably missing something obvious, but I have been trying to find that something for the last 2 hours without any luck. Any help is appreciated.
import time
import pyautogui
x = input()
time.sleep(5) #delays the next process by 5 seconds
def work():
global x
pyautogui.hotkey('ctrl','v')
time.sleep(.25)
pyautogui.press('enter')
time.sleep(.25)
x = x - 1
try:
while x > 0:
work()
else:
pass
except KeyboardInterrupt:
pass
OK i figured this out. x > 0 was the problem. As the code stands now x is a string and you can't compare a string to an integer.
So what i did was add this after the user input
x = int(x)
Now it works perfectly. If i had run the program from the command window i would have found this problem hours ago. I will know better for next time.

pyautogui locateonscreen not finding pop up

Im trying to automate a program, we use all the time:
import pyautogui, time
import PIL
input("Press Enter to start")
print("Starting program in 5 seconds")
time.sleep(5)
#open edgewise
pyautogui.hotkey("win")
pyautogui.typewrite("edgewise")
pyautogui.hotkey("Enter")
time.sleep(20)
print("Checking for error message")
a = pyautogui.locateOnScreen("ok.png")
while True:
if a == None:
print("Not Found")
break
else:
print("Found")
new0 = a[0]
new0 = new0 + 10
new1 = a[1]
new1 = new1 + 10
pyautogui.moveTo(new0,new1,duration=1)
pyautogui.click()
break
input("Finished")
So the idea of the program is that it opens the software, which during the startup it flashes up an error message (sometimes) which requires you to click ok.
Now, this program works if the program (edgewise) has already started and the error message is on-screen before I start the python script. I have even given it a sleep timer to make sure the program has opened correctly and is displaying the message in time
Any ideas
It seems that PYAutoGUI locateonscreen function only works when the program is already started, I tried to build my script to do everything including starting the application, but this causes issues.
Hope this helps others

Is it possible to resume a generator function after python program exit and the program restarts?

I am wondering if there exist a possibility where a generator function/iterator function in python can pause after keyboard interrupt and whenever the program restart the generator function resume from where it is left off? Please be clear and simple when explaining this solution.
After a bit reading on generators and the 'yield'.i've realized that generators only output a value, discard it and output another value and so forth...
The was trying to find a way to resume output for the following function after python quits
counter=0
def product(*args, repeat=1):
global counter
pools = [tuple(pool) for pool in args] * repeat
#yield pools
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
counter=counter+1
if counter>11:
yield tuple(prod)
def product_function():
for i in product('abc',repeat=3):
print(i)
print(counter)
product_function()
I finally decided to put in the a little variable called counter and once the counter is greater that the 11th word then all over values (words) are yielded and printed. I suppose i could write some codes to store the counter variable in a separate file whenever the program quits and whenever the program restarts it pulls the last counter variable from the file so that output resumes. hope this works..

Resources