473,666 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cleanly end a thread with blocked i/o in win32?

Trying to work around the lack of pexpect for native windows python I
had a play with os.popen2 and some threads. This looks promising
enough for what I want to do, but I hit on a problem with getting the
script to exit cleanly. Tried replacing popen with subprocess but I am
still confused. Either it needs to be killed from the task manager, or
I get a variety of different complaints and popping up "applicatio n
error" windows. I managed to get it to stop with os.abort(), but this
invites a complaint from windows about terminating in an unusual way.
Closing the file descriptors of the child process leads to a crash and
I think I should be sending a kill to the process, although I don't
know how (please tell me).

Would any of you care to have a look at the code below and make
suggestions for tidying it up properly? It also dies nastily if the
child process terminates. Eventually I would like to fire off a
program from a gui, supply input programmaticall y, depending upon the
unpredicable questions the program might ask, and prompt the user if
the child process asks something unknown. Also process the output into
a graphical form so the user can change options and run the child
again. Makes the crashing a bit of a problem! Entirely different
approaches which can accomplish this task would also be very very
welcome, I tried a telnet to localhost suggestion, but this was
painfully slow on this windows xp machine (using "services for unix"
telnet server). The communicate bit of subprocess only gives me one
chance to talk to the process. Should I be inheriting from subprocess
and editing the communicate method there?

Having googled extensively on this problem it seems that tidying up
this code could be useful to others too?

Thanks!!

Jon
---
import os,sys,time,sub process
from threading import Thread

out = ""

class reader(Thread):
def __init__(self,f ile_to_read):
self.file_to_re ad=file_to_read
Thread.__init__ (self)
def run(self):
global out
while 1:
i=self.file_to_ read.read(1)
out+=i
sys.stdout.writ e(i) # for debugging

class writer(Thread):
def __init__(self,f ile_to_write):
self.file_to_wr ite=file_to_wri te
Thread.__init__ (self)
def run(self):
global out
while 1:
i=sys.stdin.rea d(1) # for debugging
out+=i
self.file_to_wr ite.write(i)

if __name__=="__ma in__":
child = subprocess.Pope n(sys.argv[1],
stdin=subproces s.PIPE,
stdout=subproce ss.PIPE)
# or: child.stdout,ch ild.stdin = os.popen2(sys.a rgv[1])
r = reader(child.st dout)
w = writer(child.st din)
r.start()
w.start()
while r.isAlive() and w.isAlive():
try:
time.sleep(10)
except:
print "\n=== in out now ===\n",out,"\n= ====="
break
print r.isAlive(),w.i sAlive() # Who died, in or out??
time.sleep(1)
print r.isAlive(),w.i sAlive() # Who died, in or out??
print "You fell off of the bottom of the script"
Jul 18 '05 #1
2 3341
jo************* @gmail.com (Jon Wright) wrote in message news:<56******* *************** ****@posting.go ogle.com>...
Trying to work around the lack of pexpect for native windows python I
had a play with os.popen2 and some threads. This looks promising
enough for what I want to do, but I hit on a problem with getting the
script to exit cleanly. Tried replacing popen with subprocess but I am
still confused. Either it needs to be killed from the task manager, or
I get a variety of different complaints and popping up "applicatio n
error" windows. I managed to get it to stop with os.abort(), but this
invites a complaint from windows about terminating in an unusual way.
Closing the file descriptors of the child process leads to a crash and
I think I should be sending a kill to the process, although I don't
know how (please tell me).

Would any of you care to have a look at the code below and make
suggestions for tidying it up properly? It also dies nastily if the
child process terminates. Eventually I would like to fire off a
program from a gui, supply input programmaticall y, depending upon the
unpredicable questions the program might ask, and prompt the user if
the child process asks something unknown. Also process the output into
a graphical form so the user can change options and run the child
again. Makes the crashing a bit of a problem! Entirely different
approaches which can accomplish this task would also be very very
welcome, I tried a telnet to localhost suggestion, but this was
painfully slow on this windows xp machine (using "services for unix"
telnet server). The communicate bit of subprocess only gives me one
chance to talk to the process. Should I be inheriting from subprocess
and editing the communicate method there?

Having googled extensively on this problem it seems that tidying up
this code could be useful to others too?

Thanks!!

Jon
---
import os,sys,time,sub process
from threading import Thread

out = ""

class reader(Thread):
def __init__(self,f ile_to_read):
self.file_to_re ad=file_to_read
Thread.__init__ (self)
def run(self):
global out
while 1:
i=self.file_to_ read.read(1)
out+=i
sys.stdout.writ e(i) # for debugging

class writer(Thread):
def __init__(self,f ile_to_write):
self.file_to_wr ite=file_to_wri te
Thread.__init__ (self)
def run(self):
global out
while 1:
i=sys.stdin.rea d(1) # for debugging
out+=i
self.file_to_wr ite.write(i)

if __name__=="__ma in__":
child = subprocess.Pope n(sys.argv[1],
stdin=subproces s.PIPE,
stdout=subproce ss.PIPE)
# or: child.stdout,ch ild.stdin = os.popen2(sys.a rgv[1])
r = reader(child.st dout)
w = writer(child.st din)
r.start()
w.start()
while r.isAlive() and w.isAlive():
try:
time.sleep(10)
except:
print "\n=== in out now ===\n",out,"\n= ====="
break
print r.isAlive(),w.i sAlive() # Who died, in or out??
time.sleep(1)
print r.isAlive(),w.i sAlive() # Who died, in or out??
print "You fell off of the bottom of the script"


Just curiosity: why did you try using UNIX methods in win32?
To prove that windows isn't unix?
Jul 18 '05 #2
el*******@hotma il.com (Elbert Lev) wrote in message
jo************* @gmail.com (Jon Wright) wrote in message
Trying to work around the lack of pexpect for native windows python I
had a play with os.popen2 and some threads. This looks promising
Just curiosity: why did you try using UNIX methods in win32?


I am after a particular functionality - I don't care what methods are
used; I just want to save myself repetitively typing crap into a
program and only answer the interesting questions it asks. Starting
another program and communicating programmaticall y via stdin and
stdout (usually defined in a language specification) is a convenience
for any multitasking os. Your suggestion helps a great deal however -
one just needed to know the translation into win32 for 'kill'. In my
case this seems sufficient:

def kill_win32(chil d):
import win32api, win32con
child.stdin.clo se() # should really check if this is open etc
handle = win32api.OpenPr ocess(win32con. PROCESS_TERMINA TE,
0,[child.pid])
win32api.CloseH andle(handle)
child.stdout.cl ose() # ditto
# error handling

Doubtless other children would resist this and some stronger magic
could be needed to snuff them out?

Perhaps this would be a useful thing to put into the "subprocess .py"
module which I think has now become part of the standard library...?
Probably a windows expert can do much better, and eventually lines
saying if win32 do this, if unix do that. Does that need a PEP or a
patch or is someone going to tell me why it shouldn't be there? Maybe
calling it "child.try_to_k ill()" is enough to indicate that it won't
always work?
To prove that windows isn't unix?


Thanks for your comment. Highly motivating. I now have roughly the
functionality I wanted on both platforms. You hint at the idea that
there is a way to achieve the goal via "win32 methods". I am still
extremely curious to know what these methods might be, I only found
stories that they don't exist in the general case of win32 console io.
Since cygwin python has pty/pexpect modules and runs under win32 the
"proof" fails by contradication?
Jon
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
2509
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise Error # Error is subclass of Exception
3
2211
by: David Sworder | last post by:
This message was already cross-posted to C# and ADO.NET, but I forgot to post to this "general" group... sorry about that. It just occured to me after my first post that the "general" group readers might have some thoughts on this perplexing .NET blocking issue. (see below) ===== Hi,
4
4929
by: Dr. J | last post by:
How to terminate a blocked thread? In my form's "load" I launch a TCP listening thread that stays in an infinite loop waiting for incoming TCP packets. In this form's "closing" I try to terminate this thread by calling the "Abort" funcion. But the thread does not terminate and after the form is closed this thread keeps running at blocked state. Basically the application keeps running because this thread does not terminate while...
6
4107
by: roger beniot | last post by:
I have a program that launches multiple threads with a ThreadStart method like the following (using System.Net.Sockets.Socket for UDP packet transfers to a server): ThreadStart pseudo code: Connect Receive response Send Connect ACK
3
3579
by: Boniek | last post by:
Hi My main thread is waiting for data from database ( opened Sqlconnection etc) and my Main Form is also blocked. I have a ProgressBar on Status Bar which show to a user how percent data is loaded. I use ThreadTimer and Thread but I can't do anything because when a thread (or ThreadTimer) go to the line ProgressBar.PefromStep() then it stop on that line. I think it's work like that because the Main Thread (and main Form) is sleeping....
3
2844
by: Andrew Baker | last post by:
OK this has me perplexed, puzzled and bamboozled! I have a remoting service which I displayed a message box in. I then wondered what would happen if a client made a call to the service while the message box was being displayed. Since the call comes in on a different thread the client call was not blocked. This seemed to make sense to me. Next I thought, what will happen when the client calls into the server if I try to use a delegate...
13
2060
by: Paul | last post by:
Hi, How do I wait until a thread is finished his job then continue to the original thread? public void main(string args) { Thread t = new Thread(new ThreadStart(DoWork)); t.Start();
5
2596
by: Bill Davidson | last post by:
Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things, sinks events from outside sources. I realize the worker thread will be interrupted to handle an incoming event (and the flow of execution subsequently diverted to the respective event handler). My question is at what point or points could this interruption occur. Will it only occur when the worker thread is...
14
37371
by: Joe | last post by:
Does anyone know the difference, in practical terms, between Thread.Sleep (10000) and Thread.CurrentThread.Join (10000)?? The MSDN says that with Join, standard COM and SendMessage pumping continues, but what does this mean in practice for a typical Windows Forms or Windows Service application?? Some people say you should always use the latter.
0
8440
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8355
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8550
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8638
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6191
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4193
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2006
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1769
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.