I want to make my input continue after a new line is created in the terminal.
Here's the quick script I wrote:
import threading, time
def inn():
while True:
input()
def count():
a=0
while True:
a+=1
print(a)
time.sleep(1)
t1 = threading.Thread(target=inn)
t2 = threading.Thread(target=count)
t1.start()
t2.start()
Is there any way I could accomplish this, preferably with in-built functions.
if you change your code to:
.
def inn(): # in is restricted name in python
while True:
print(input())
.
.
.
you will notice that your code already does what you want! Even though it doesn't look like so, the input is not interrupted, take a look at the program:
1
2
t3
his 4
iss 5
my 6
strin7
g 8
this iss my string
9
The only change your code needs is to change restricted name in.
Related
import time
i = 1
def sendData(x):
time.sleep(5)
print("delayed data: ", x)
while (1):
print(i)
sendData(i)
i += 1
time.sleep(0.5)
What I want is to print a value every 5 seconds while the infinite loop runs.
so I can see the values printing very .5 seconds and another value being printed every 5 seconds.
At the moment, the loop still gets delayed because of the time.sleep(5) in the helper function. Any help is appreciated. Thank you.
You can achieve your goal using the threading library. It allows you to run code in the "background" while your main code runs alongside it.
Here's an example of how to run the sendData function in the background with the main loop executing concurrently. Notice that I modified sendData to use the global variable i instead of receiving it as a parameter to allow the main loop to update i.
import threading
import time
i = 1
def sendData():
while True:
time.sleep(5)
print("delayed data: ", i)
thread = threading.Thread(target=sendData)
thread.start()
while (1):
print(i)
i += 1
time.sleep(0.5)
You can read more about threading and sharing variables when using threading.
You could achieve this with an asynchronous approach or use multi-[threading|procesiing]
Your approach is blocking the execution as it runs step by step.
Choosing the approach depends on the task that you want to perform in the sendData method, but from the name, I could suggest asyncio should work just fine.
import asyncio
async def send_data(x):
await asyncio.sleep(5) # Could be network request as well
print("delayed data: ", x)
async def main():
i = 1
while True:
print(i)
# Create non blocking task (run in background)
asyncio.create_task(send_data(i))
i += 1
await asyncio.sleep(0.5)
if __name__ == '__main__':
asyncio.run(main())
This code may help you. But, you need to modify them as you want
# importing module
import time
# running loop from 0 to 4
for i in range(0,5):
# printing numbers
print("delayed data: ", i)
# adding 0.5 seconds time delay
time.sleep(0.5)
the output print every 0.5 sec like this:
delayed data: 0
delayed data: 1
delayed data: 2
delayed data: 3
delayed data: 4
I'm trying to implement a multi thread program in python and am having troubles.
I try to design a program, when the program (main thread) receives a specific command,
The counter of the program will return to the previous number and continue counting down.
The following is the code I tried to write:
import threading
import time
count = 0
preEvent = threading.Event()
runEvent = threading.Event()
runEvent.set()
preEvent.clear()
def pre():
global count
while True:
if event.isSet():
count -= 1
event.clear()
def doSomething():
global count
while True:
# if not runEvent.isSet():
# runEvent.wait()
print(count)
count += 1
time.sleep(1)
def main():
t1 = threading.Thread(target=pre, args=())
t2 = threading.Thread(target=doSomething, args=())
t1.start()
t2.start()
command = input("input command")
while command != 'quit':
command = input("input command")
if command == 'pre':
preEvent.set()
main()
But I encountered a few problems
How to block t1 simultaneously while I inputting a specific command
How to start from the beginning when t1 is restored instead of starting from the blocked point
Regarding question 1, I tried adding a condition check before the print(count) command, but if I enter the "pre" command when the program outputs count, the program will still perform count+=1
After that, the program will go back to check the conditions and block t1, but this does not achieve the synchronization effect I wanted.
Is there a way to achieve this goal?
Question 2 is similar to question 1. I hope that whenever I enter the command, my program will output like this.
1
2
3
4
pre
3
4
...
But if t1 is blocked after finishing the print(count) instruction, when the event is cleared, t1 will continue to execute from count+=1
So the output will become the following
1
2
3
4
pre
4
5
...
I tried to find information on the Internet, but I never knew how to add keywords.
Is there a method or library that can achieve this function?
I have tried my best to describe my problem, but it may not be good enough. If I have any questions about my problem, I can add more explanation.
Thank you all for your patience to read my question
The threading module has a wait method that will block until notify or notify_all is called. This should accomplish what you're looking for in your first question. For question 2 you can either define a function that handles the exit case, or just recreate a thread to start form the beginning.
Simply it can work like this, maybe helps.
from threading import Thread, Event
count = 0
counter = Event()
def pre():
global count
counter.wait()
count -= 1
print(count)
def main():
global count
print(count)
while True:
command = input("Enter 1 to increase, Enter 2 to decrease :")
if command == "1":
t1 = Thread(target=pre, args=())
t1.start()
counter.set()
else :
count += 1
print(count)
main()
So I’m trying to have a strobe like effect on a game I’m building and the way I currently have it it’s destroying my frame rate because the sleep function is also applying to the draw function. Can someone explain why this happens? And the logic that I’m failing to understand. Why can’t I just have the return happen every .5 seconds without it affecting the .1 sleep I have in my hue function?
Here’s a crude demonstration of what the code kind of does.
from random import randint
import time
def rand_intr():
r = randint(1,256)
time.sleep(.5)
return r
def rand_intg():
g = randint(1,256)
time.sleep(.5)
return g
def rand_intb():
b = randint(1,256)
time.sleep(.5)
return b
def hue():
r = rand_intr()
g = rand_intg()
b = rand_intb()
print(r, g, b)
print('test')
time.sleep(.01)
while True:
hue()
The sleep function blocks the main thread. This means rand_intg does not run until rand_intr "wakes up" from its sleep.
Similarly, rand_intb has to wait for rand_intg, and hue has to wait for all the previous 3 functions. This means the total time hue has to wait before it can do any work is at least the amount of time needed to complete rand_intr, rand_intg, and rand_intb.
We can understand what is happening if we modify your example slightly and look at the output.
from random import randint
import time
def log_entry_exit(f):
def wrapped():
print("Entered {}".format(f.__name__))
result = f()
print("Leaving {}".format(f.__name__))
return result
return wrapped
#log_entry_exit
def rand_intr():
r = randint(1,256)
time.sleep(.5)
return r
#log_entry_exit
def rand_intg():
g = randint(1,256)
time.sleep(.5)
return g
#log_entry_exit
def rand_intb():
b = randint(1,256)
time.sleep(.5)
return b
def hue():
r = rand_intr()
g = rand_intg()
b = rand_intb()
print(r, g, b)
print('test')
time.sleep(.01)
while True:
hue()
Here I just modified your functions to print a message when we enter and exit each function.
The output is
Entered rand_intr
Leaving rand_intr
Entered rand_intg
Leaving rand_intg
Entered rand_intb
Leaving rand_intb
172 206 115
test
Entered rand_intr
Leaving rand_intr
Entered rand_intg
Leaving rand_intg
Entered rand_intb
Leaving rand_intb
240 33 135
test
...
Here, the effect of each sleep on hue can be seen clearly. You don't get to print the rgb values or "test" until the previous functions have completed.
What you can do is to call your hue function periodically using a timer callback, and then modify the rgb values according to some pattern. See this stackoverflow question on
executing periodic actions for an example on how to periodically execute a function using a basic time-based mechanism.
Edit
Based on your comment to #jasonharper
If you call hue every 60 seconds, it does not make sense if your calls to the functions that generate the random rgb values occur at a faster rate because any changes in the intervening time will not be seen in hue.
What you can do is call hue every 60 seconds, then generate your rgb values to have whatever pattern in there.
Modifying the answer by #kev in the post I linked to above,
import time, threading
def update():
# Do whatever you want here.
# This function will be called again in 60 seconds.
# ...
hue()
# Whatever other things you want to do
# ...
threading.Timer(60.0, update).start()
def hue():
r = rand_intr()
g = rand_intg()
b = rand_intb()
print(r, g, b)
# Don't call sleep.
if __name__ == "__main__":
update()
Now you should only call update once, possibly in some startup part of your code and remove all the calls to sleep in your functions.
So I have been messing around with this multithreading all day long but can seem to get it to work. It's in Python 3 also.
The program is trying to generate a list of 5 words 1000 times and using multithreading to increase the speed.
I've changed the code to lots off different methods im been searching online but with no outcome.
With what I have at the moment it will run without any issue but not print any of the words.
Any chance someone could have a look over it.
import random
from threading import Thread
word_file = "words.txt"
def gen():
Words = open(word_file).read().splitlines() #retreiving and sorting word file
seed = random.randrange(0,2048) #amount of words to choose from in list
for x in range(0, 1000):
print(random.choices(Words, k=5)) #print the words
def main():
t1 = Thread(target=gen)
t2 = Thread(target=gen)
t3 = Thread(target=gen)
t4 = Thread(target=gen)
t1.start()
t2.start()
t3.start()
t4.start()
print("completed")
Very simple: Your code is not calling any function, but just building them and leaving them alone.
Just add main() right before print("completed") so the code calls that function.
Note 1: Why are you reading the text file over and over again inside the loop, and why opening it manually? Auto-close it by the:
with open(word_file, "r") as f:
Words = f.read().splitlines()
code before gen().
Note 2: What is seed doing? You defined it but haven't used it anywhere.
Note 3: Please check your indentation before posting a question.
I'm intermidiate bee for python and would like to run the same class instances of few in parallel mode for fetching data and decision making for financial market. To proceed my idea, I run the following code to see how python works, it seems it works one complete run of first class instance and after second class instances, I would like to run this parallely, how can I...?
Below is the some sample code for testing..
import threading
import time
class thr(object):
def __init__(self, name):
self.name = name
self.x = 0
def run(self):
for i in list(range(10)):
self.x +=1
print("something {0} {1}".format(self.name, self.x))
time.sleep(1)
F = thr("First")
S = thr("Second")
threading.Thread(target=F.run())
threading.Thread(target=S.run())
and the results as below....
something First 1
something First 2
something First 3
something First 4
something First 5
something First 6
something First 7
something First 8
something First 9
something First 10
something Second 1
something Second 2
something Second 3
something Second 4
something Second 5
something Second 6
something Second 7
something Second 8
something Second 9
something Second 10
Out[27]: <Thread(Thread-25, initial)>
The problem is here:
threading.Thread(target=F.run())
threading.Thread(target=S.run())
target= takes a callable object or None. F.run() executes F.run immediately, waits for it finish, and then passes the return value (which is None in your run() method) as the target.
You want something like this instead:
t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()
Note that there's no parentheses after run
Here's the complete program with the suggested change:
import threading
import time
class thr(object):
def __init__(self, name):
self.name = name
self.x = 0
def run(self):
for i in list(range(10)):
self.x +=1
print("something {0} {1}".format(self.name, self.x))
time.sleep(1)
F = thr("First")
S = thr("Second")
t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()
And output (Python 3.6.1):
$ python sf.py
something First 1
something Second 1
something Second 2
something First 2
something Second 3
something First 3
something Second 4
something First 4
something Second 5
something First 5
something Second 6
something First 6
something Second 7
something First 7
something First 8
something Second 8
something First 9
something Second 9
something First 10
something Second 10