Async subprocess context manager

2019-09-01 Thread Peter Sutton
Hi all,

First time posting! I need an async context manager that ensures a
Process has finished before it `__exit__()`s, either by graceful or
forceful termination, and regardless of cancellation. I've put my code
at the bottom.

I'm relatively new to asyncio, so I'm looking for feedback on any
aspect of the code. Not only correctness, but things like if I'm
handling cancellation correctly or is the a more idiomatic way to go
back this?

Thanks,


Peter.


```
from __future__ import annotations
import asyncio
import time
from contextlib import asynccontextmanager
from typing import AsyncIterator, Optional


@asynccontextmanager
async def terminating(proc: asyncio.subprocess.Process, timeout: float) \
-> AsyncIterator[asyncio.subprocess.Process]:
try:
yield proc
finally:
try:
proc.terminate()
except ProcessLookupError:
pass
else:
start = time.time()
while True:
remaining = timeout - (time.time() - start)
try:
await asyncio.wait_for(proc.wait(), remaining)
except asyncio.CancelledError:
is_done = False
is_cancelled = True
except asyncio.TimeoutError:
is_done = False
is_cancelled = False
break
else:
print('Terminated')
is_done = True
is_cancelled = False
break
if not is_done:
try:
proc.kill()
except ProcessLookupError:
pass
else:
while True:
try:
proc.wait()
except asyncio.CancelledError:
is_cancelled = True
else:
print('Killed')
break
if is_cancelled:
raise asyncio.CancelledError()


async def test(sleep: float) -> None:
proc = await asyncio.create_subprocess_shell('sleep 10')
async with terminating(proc, 1):
await asyncio.sleep(sleep)


async def main():
await test(1)

task = asyncio.create_task(test(1))
task.cancel()
try:
await task
except asyncio.CancelledError:
pass


asyncio.run(main())
```
-- 
https://mail.python.org/mailman/listinfo/python-list


Clipboard Monitor (tkinter,windows)

2007-08-24 Thread Peter Sutton
Hi. I am an A-level student studying computer science. I have taken it upon 
myself to learn python. It is now my weapon of choice. I have had a problem 
trying to creating a clipboard monitor in Windows(XP,Vista) that is linked to a 
tkinter GUI. I have a perfectly good code for clipboard monitoring, but as soon 
as it is linked to a tkinter gui, the gui locks when a WM.DRAWCLIPBOARD message 
is recieved. I am at the point of giving up. If anyone can help or offer an 
alternativethat is not pollingI would be very happy.  Thanks. Peter

import win32ui, win32clipboard, win32con, win32api, win32gui
from Tkinter import *

def paste():
win32clipboard.OpenClipboard(0)
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return data


class ClipRecord(object):
def __init__(self):
self.gui = Tk()
self.hPrev = 0
self.first = True
self.win = win32ui.CreateFrame()
self.win.CreateWindow(None,'',win32con.WS_OVERLAPPEDWINDOW)
self.win.HookMessage(self.OnDrawClipboard,win32con.WM_DRAWCLIPBOARD)
self.win.HookMessage(self.OnChangeCBChain,win32con.WM_CHANGECBCHAIN)
self.win.HookMessage(self.OnDestroy,win32con.WM_DESTROY)
try:
self.hPrev=win32clipboard.SetClipboardViewer(self.win.GetSafeHwnd())
except win32api.error, err:
if win32api.GetLastError () == 0:
# information that there is no other window in chain
pass
else:
raise
self.l = Label(self.gui,text="I have losted the will to live")
self.l.pack()
self.gui.mainloop()
def OnChangeCBChain(self, *args):
msg, wParam, lParam = args[-1][1:4]
if self.hPrev == wParam:
# repair the chain
self.hPrev = lParam
if self.hPrev:
# pass the message to the next window in chain
win32api.SendMessage (self.hPrev, msg, wParam, lParam)

def OnDrawClipboard(self, *args):
msg, wParam, lParam = args[-1][1:4]
if self.first:
self.first = False
else:
self.l["text"] = "Lord be Praised"
print paste()
if self.hPrev:
# pass the message to the next window in chain
win32api.SendMessage (self.hPrev, msg, wParam, lParam)
def OnDestroy(self):
if self.hPrev:

win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(),self.hPrev)
else:
win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(),0)

if __name__ == "__main__":
cr = ClipRecord()




  ___
Yahoo! Answers - Got a question? Someone out there knows the answer. Try it
now.
http://uk.answers.yahoo.com/ -- 
http://mail.python.org/mailman/listinfo/python-list