python: how to interrupt raw_input() in other thread

  • Last Update :
  • Techknowledgy :

You could just make the sending thread daemonic:

send_thread = SendThread() # Assuming this inherits from threading.Thread
send_thread.daemon = True # This must be called before you call start()

Suggestion : 2

The Python interpreter won't be blocked from exiting if the only threads left running are daemons. So, if the only thread left is send_thread, your program will exit, even if you're blocked on raw_input.,Note that this will terminate the sending thread abruptly, no matter what its doing. This could be dangerous if it accesses external resources that need to be cleaned up properly or shouldn't be interrupted (like writing to a file, for example). If you're doing anything like that, protect it with a threading.Lock, and only call sys.exit() from the receiving thread if you can acquire that same Lock.,You could just make the sending thread daemonic:

You could just make the sending thread daemonic:

send_thread = SendThread() # Assuming this inherits from threading.Thread
send_thread.daemon = True # This must be called before you call start()

Suggestion : 3

By Bernd Klein. Last modified: 01 Feb 2022.

Example for a Thread in Python:

from thread
import start_new_thread

def heron(a):
   ""
"Calculates the square root of a"
""
eps = 0.0000001
old = 1
new = 1
while True:
   old, new = new, (new + a / new) / 2.0
print old, new
if abs(new - old) < eps:
   break
return new

start_new_thread(heron, (99, ))
start_new_thread(heron, (999, ))
start_new_thread(heron, (1733, ))

c = raw_input("Type something to quit.")

We expand the previous example with counters for the threads.

from thread
import start_new_thread

num_threads = 0
def heron(a):
   global num_threads
num_threads += 1

# code has been left out, see above
num_threads -= 1
return new

start_new_thread(heron, (99, ))
start_new_thread(heron, (999, ))
start_new_thread(heron, (1733, ))
start_new_thread(heron, (17334, ))

while num_threads > 0:
   pass

The solution with locks looks like this:

from thread
import start_new_thread, allocate_lock
num_threads = 0
thread_started = False
lock = allocate_lock()
def heron(a):
   global num_threads, thread_started
lock.acquire()
num_threads += 1
thread_started = True
lock.release()

   ...

   lock.acquire()
num_threads -= 1
lock.release()
return new

start_new_thread(heron, (99, ))
start_new_thread(heron, (999, ))
start_new_thread(heron, (1733, ))

while not thread_started:
   pass
while num_threads > 0:
   pass

The previous script returns the following output:

thread 0 sleeps
for 5 seconds
thread 1 sleeps
for 5 seconds
thread 2 sleeps
for 5 seconds
thread 3 sleeps
for 5 seconds
thread 4 sleeps
for 5 seconds
thread 5 sleeps
for 5 seconds
thread 6 sleeps
for 5 seconds
thread 7 sleeps
for 5 seconds
thread 8 sleeps
for 5 seconds
thread 9 sleeps
for 5 seconds
thread 1 woke up
thread 0 woke up
thread 3 woke up
thread 2 woke up
thread 5 woke up
thread 9 woke up
thread 8 woke up
thread 7 woke up
thread 6 woke up
thread 4 woke up

The next example shows a thread, which determines, if a number is prime or not. The Thread is defined with the threading module:

import threading

class PrimeNumber(threading.Thread):
   def __init__(self, number):
   threading.Thread.__init__(self)
self.Number = number

def run(self):
   counter = 2
while counter * counter < self.Number:
   if self.Number % counter == 0:
   print "%d is no prime number, because %d = %d * %d" % (self.Number, self.Number, counter, self.Number / counter)
return
counter += 1
print "%d is a prime number" % self.Number
threads = []
while True:
   input = long(raw_input("number: "))
if input < 1:
   break

thread = PrimeNumber(input)
threads += [thread]
thread.start()

for x in threads:
   x.join()

Suggestion : 4

Use a second thread (https://en.wikipedia.org/wiki/Multithreading_(computer_architecture), How to use threading in Python?):,This will work as you intended except that it will overwrite the file a new each time new data is sent without timing out. Timeout represents end of whole connection. But you can easily rework this to add data to same file or create a new file or do whatever you need.,This is happening because you're not using an if __name__ == "__main__": guard, while also using multiprocessing.Process on Windows. Windows needs to re-import your module in the child processes it spawns, which means it will keep creating new threads to handle inputs and watch files. This, of course, is a recipe for disaster. Do this to fix the issue:,Here is a multi-threaded example. This code will work with the python interpreter but not with the Python Shell of IDLE, because the raw_input function is not handled the same way.

if __name__ == "__main__":
   iw = threading.Thread(target = input_watcher)
fw = threading.Thread(target = file_watcher)

iw.start()
fw.start()
from threading
import Thread
from time
import sleep

class A(Thread):
   def __init__(self):
   Thread.__init__(self)
self.value = 1
self.stop_flag = False

def run(self):
   while not self.stop_flag:
   sleep(1)
print(self.value)

def set_value(self, value):
   self.value = value

def stop(self):
   self.stop_flag = True

if __name__ == '__main__':
   a = A()
a.start()
try:
while 1:
   r = raw_input()
a.set_value(int(r))
except:
   a.stop()
leaving = False
while not leaving:

   user_ip = raw_input("Do you want to continue sniffing???(y/n)")
if user_ip.lower() == 'y':
   new_thread = Thread(target = sniffer, args = (ip, ))
new_thread.start()
new_thread.join()
elif user_ip.lower() == 'n':
   print "Leaving sniffer"
leaving = True
return
def quit_on_user_input():
   input = raw_input("Press any key to quit.")
# thread will lock up and wait
for user to input.That 's why this is on a separate thread.
sys.exit(0)

quit_thread = threading.Thread(target = quit_on_user_input, args = [])
quit_trhead.start()
# The rest of your code.quit_thread will run in the background and therefor won 't lock up your main thread.
#! /usr/bin/env python

from socket
import AF_INET, SOCK_DGRAM
import socket
import threading

class Server(threading.Thread):
   def __init__(self, host = "192.168.88.51", port = 123, bufsize = 128):
   threading.Thread.__init__(self)
self.host = host
self.port = port
self.bufsize = bufsize
self.done = threading.Event()

def opensock(self):
   s = socket.socket(AF_INET, SOCK_DGRAM)
s.bind((self.host, self.port))
s.settimeout(0.001)
return s

def run(self):
   host = self.host
port = self.port
self.s = s = self.opensock()
print "Waiting for connection on", host + ":" + str(port)
while not self.done.isSet():
   try:
   data, addr = s.recvfrom(self.bufsize)
print "Connection from", addr
s.settimeout(1)
self.recvdata(data, s, addr)
s.settimeout(0.001)
except socket.timeout: pass
except:
   raise
self.done.set()
s.close()
print "Server on '%s:%s' stopped!" % (host, port)

def recvdata(self, initdata, conn, addr):
   bufsize = self.bufsize
filename = str(self.port) + ".data"
print "Opening file", filename
f = open(filename, "wb")
print "Receiving & writingrest of data from", addr
data = initdata
while data and not self.done.isSet():
   f.write(data)
try:
data, addr = conn.recvfrom(bufsize)
except socket.timeout: break
f.close()
if self.done.isSet():
   print "Forcefully interrupted transmission"
else:
   print "File Downloaded"

def stop(self):
   self.done.set()
self.s.close()

servers = []
for port in xrange(123, 150):
   try:
   s = Server(port = port)
s.start()
servers.append(s)
except Exception as e:
   print e

raw_input("Press enter to send data to one of ports for testing . . . ")
import random
a = servers[0].host
p = random.choice(servers).port
print "data will be sent to port '%s:%i'" % (a, p)
k = socket.socket(AF_INET, SOCK_DGRAM)
k.connect((a, p))
k.send("1234567890")
k.send("asdfghjkl")
k.send("0987654321")
k.close()
raw_input("Press enter to close the program . . . ")

# Stop all servers:
   for s in servers:
   s.stop()

# Make sure all of them terminated:
   for s in servers:
   s.join()

Suggestion : 5

A multiprocessing.Process can p.terminate() In the cases where I want to ...READ MORE,but threads_list does not contain the thread that was started, even when I know the thread is still running. Can anyone help me solve this issue?,The key is to start the thread using threading, not thread:,How can I see whether a thread has completed? I tried the following code:

How can I see whether a thread has completed? I tried the following code:

import thread
import threading

id1 = thread.start_new_thread(my_function, ())
#wait some time
threads_list = threading.enumerate()
# Want to know
if my_function() that was called by thread id1 has returned

def my_function()
#do stuff
return

The key is to start the thread using threading, not thread:

t1 = threading.Thread(target = my_function, args = ())
t1.start()

Then use

z = t1.isAlive()

or

l = threading.enumerate()