def execute (cmd, timeout = 0):
if timeout == 0:
timeout = win32event.INFINITE
info = win32process.CreateProcess(None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO())
subprocess = info [0]
rc = win32event.WaitForSingleObject (subprocess, timeout)
if rc == win32event.WAIT_FAILED:
return -1
if rc == win32event.WAIT_TIMEOUT:
try:
win32process.TerminateProcess (subprocess, 0)
except pywintypes.error:
return -3
return -2
if rc == win32event.WAIT_OBJECT_0:
return win32process.GetExitCodeProcess(subprocess)
python类WaitForSingleObject()的实例源码
def run_elevated(command, args, wait=True):
"""Run the given command as an elevated user and wait for it to return"""
ret = 1
if command.find(' ') > -1:
command = '"' + command + '"'
if platform.system() == 'Windows':
import win32api
import win32con
import win32event
import win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
logging.debug(command + ' ' + args)
process_info = ShellExecuteEx(nShow=win32con.SW_HIDE,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb='runas',
lpFile=command,
lpParameters=args)
if wait:
win32event.WaitForSingleObject(process_info['hProcess'], 600000)
ret = win32process.GetExitCodeProcess(process_info['hProcess'])
win32api.CloseHandle(process_info['hProcess'])
else:
ret = process_info
else:
logging.debug('sudo ' + command + ' ' + args)
ret = subprocess.call('sudo ' + command + ' ' + args, shell=True)
return ret
def timeout_execute (cmd, timeout = 0):
if timeout == 0:
timeout = win32event.INFINITE
info = win32process.CreateProcess(None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO())
subprocess = info [0]
rc = win32event.WaitForSingleObject (subprocess, timeout)
if rc == win32event.WAIT_FAILED:
return -1
if rc == win32event.WAIT_TIMEOUT:
try:
win32process.TerminateProcess (subprocess, 0)
except pywintypes.error:
return -3
return -2
if rc == win32event.WAIT_OBJECT_0:
return win32process.GetExitCodeProcess(subprocess)
def run(self):
last_time = os.stat(self.filename)[stat.ST_MTIME]
while 1:
try:
rc = win32event.WaitForSingleObject(self.handle,
win32event.INFINITE)
win32file.FindNextChangeNotification(self.handle)
except win32event.error, details:
# handle closed - thread should terminate.
if details.winerror != winerror.ERROR_INVALID_HANDLE:
raise
break
this_time = os.stat(self.filename)[stat.ST_MTIME]
if this_time != last_time:
print "Detected file change - flagging for reload."
self.change_detected = True
last_time = this_time
def run(self):
last_time = os.stat(self.filename)[stat.ST_MTIME]
while 1:
try:
rc = win32event.WaitForSingleObject(self.handle,
win32event.INFINITE)
win32file.FindNextChangeNotification(self.handle)
except win32event.error as details:
# handle closed - thread should terminate.
if details.winerror != winerror.ERROR_INVALID_HANDLE:
raise
break
this_time = os.stat(self.filename)[stat.ST_MTIME]
if this_time != last_time:
print("Detected file change - flagging for reload.")
self.change_detected = True
last_time = this_time
def run(self):
last_time = os.stat(self.filename)[stat.ST_MTIME]
while 1:
try:
rc = win32event.WaitForSingleObject(self.handle,
win32event.INFINITE)
win32file.FindNextChangeNotification(self.handle)
except win32event.error as details:
# handle closed - thread should terminate.
if details.winerror != winerror.ERROR_INVALID_HANDLE:
raise
break
this_time = os.stat(self.filename)[stat.ST_MTIME]
if this_time != last_time:
print("Detected file change - flagging for reload.")
self.change_detected = True
last_time = this_time
def testNotifyChange(self):
def change():
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
try:
win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo")
finally:
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
evt = win32event.CreateEvent(None,0,0,None)
## REG_NOTIFY_CHANGE_LAST_SET - values
## REG_CHANGE_NOTIFY_NAME - keys
## REG_NOTIFY_CHANGE_SECURITY - security descriptor
## REG_NOTIFY_CHANGE_ATTRIBUTES
win32api.RegNotifyChangeKeyValue(win32con.HKEY_CURRENT_USER,1,win32api.REG_NOTIFY_CHANGE_LAST_SET,evt,True)
ret_code=win32event.WaitForSingleObject(evt,0)
# Should be no change.
self.failUnless(ret_code==win32con.WAIT_TIMEOUT)
change()
# Our event should now be in a signalled state.
ret_code=win32event.WaitForSingleObject(evt,0)
self.failUnless(ret_code==win32con.WAIT_OBJECT_0)
def wait(self, state, interval=0.1, channel=None):
"""Wait for the given state(s), KeyboardInterrupt or SystemExit.
Since this class uses native win32event objects, the interval
argument is ignored.
"""
if isinstance(state, (tuple, list)):
# Don't wait for an event that beat us to the punch ;)
if self.state not in state:
events = tuple([self._get_state_event(s) for s in state])
win32event.WaitForMultipleObjects(
events, 0, win32event.INFINITE)
else:
# Don't wait for an event that beat us to the punch ;)
if self.state != state:
event = self._get_state_event(state)
win32event.WaitForSingleObject(event, win32event.INFINITE)
def wait(self, state, interval=0.1, channel=None):
"""Wait for the given state(s), KeyboardInterrupt or SystemExit.
Since this class uses native win32event objects, the interval
argument is ignored.
"""
if isinstance(state, (tuple, list)):
# Don't wait for an event that beat us to the punch ;)
if self.state not in state:
events = tuple([self._get_state_event(s) for s in state])
win32event.WaitForMultipleObjects(
events, 0, win32event.INFINITE)
else:
# Don't wait for an event that beat us to the punch ;)
if self.state != state:
event = self._get_state_event(state)
win32event.WaitForSingleObject(event, win32event.INFINITE)
def pipe(bufsize=8192):
"""Creates overlapped (asynchronous) pipe.
"""
name = r'\\.\pipe\pycos-pipe-%d-%d' % (os.getpid(), next(_pipe_id))
openmode = (win32pipe.PIPE_ACCESS_INBOUND | win32file.FILE_FLAG_OVERLAPPED |
FILE_FLAG_FIRST_PIPE_INSTANCE)
pipemode = (win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE)
rh = wh = None
try:
rh = win32pipe.CreateNamedPipe(
name, openmode, pipemode, 1, bufsize, bufsize,
win32pipe.NMPWAIT_USE_DEFAULT_WAIT, None)
wh = win32file.CreateFile(
name, win32file.GENERIC_WRITE | winnt.FILE_READ_ATTRIBUTES, 0, None,
win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None)
overlapped = pywintypes.OVERLAPPED()
# 'yield' can't be used in constructor so use sync wait
# (in this case it is should be okay)
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
rc = win32pipe.ConnectNamedPipe(rh, overlapped)
if rc == winerror.ERROR_PIPE_CONNECTED:
win32event.SetEvent(overlapped.hEvent)
rc = win32event.WaitForSingleObject(overlapped.hEvent, 1000)
overlapped = None
if rc != win32event.WAIT_OBJECT_0:
pycos.logger.warning('connect failed: %s' % rc)
raise Exception(rc)
return (rh, wh)
except:
if rh is not None:
win32file.CloseHandle(rh)
if wh is not None:
win32file.CloseHandle(wh)
raise
def pipe(bufsize=8192):
"""Creates overlapped (asynchronous) pipe.
"""
name = r'\\.\pipe\pycos-pipe-%d-%d' % (os.getpid(), next(_pipe_id))
openmode = (win32pipe.PIPE_ACCESS_INBOUND | win32file.FILE_FLAG_OVERLAPPED |
FILE_FLAG_FIRST_PIPE_INSTANCE)
pipemode = (win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE)
rh = wh = None
try:
rh = win32pipe.CreateNamedPipe(
name, openmode, pipemode, 1, bufsize, bufsize,
win32pipe.NMPWAIT_USE_DEFAULT_WAIT, None)
wh = win32file.CreateFile(
name, win32file.GENERIC_WRITE | winnt.FILE_READ_ATTRIBUTES, 0, None,
win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None)
overlapped = pywintypes.OVERLAPPED()
# 'yield' can't be used in constructor so use sync wait
# (in this case it is should be okay)
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
rc = win32pipe.ConnectNamedPipe(rh, overlapped)
if rc == winerror.ERROR_PIPE_CONNECTED:
win32event.SetEvent(overlapped.hEvent)
rc = win32event.WaitForSingleObject(overlapped.hEvent, 1000)
overlapped = None
if rc != win32event.WAIT_OBJECT_0:
pycos.logger.warning('connect failed: %s' % rc)
raise Exception(rc)
return (rh, wh)
except:
if rh is not None:
win32file.CloseHandle(rh)
if wh is not None:
win32file.CloseHandle(wh)
raise
def notifyOnExit(self, processHandle, processTransport):
processHandleKey = self.phandleToPhandleKey[processHandle]
# If there are available threads, use one of them
if len(self.availableThreads) > 0:
wfmoThread = self.availableThreads[0]
self.threadToNumProcessHandles[wfmoThread] += 1
self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread
# Update used/available thread lists
if self.threadToNumProcessHandles[wfmoThread] == 63:
self.usedThreads.append(wfmoThread)
self.availableThreads.remove(wfmoThread)
# Make sure the message window has been created so
# we can send messages to the thread.
if self.threadToMsgWindowCreated[wfmoThread] is False:
val = WaitForSingleObject(self.threadToMsgWindowCreationEvent[wfmoThread], INFINITE)
if val != WAIT_OBJECT_0:
raise RuntimeError("WaitForSingleObject returned %d. It should only return %d" % (val, WAIT_OBJECT_0))
# Notify the thread that it should wait on the process handle.
if win32api.PostMessage(
self.threadToMsgWindow[wfmoThread],
WM_NEW_PHANDLE, # message
processHandleKey, # wParam
0 # lParam
) == 0:
raise Exception("Failed to post thread message!")
else:
# Create a new thread and wait on the proc handle
wfmoThread = threading.Thread(
target=self.doWaitForProcessExit,
args=(processHandleKey,),
name="iocpreactor.process_waiter.ProcessWaiter.waitForProcessExit pid=%d" % self.realPid)
# Create a window creation event that will be triggered from the thread
self.threadToMsgWindowCreationEvent[wfmoThread] = CreateEvent(None, 0, 0, None)
self.threadToMsgWindowCreated[wfmoThread] = False
self.threadToNumProcessHandles[wfmoThread] = 1
self.availableThreads.append(wfmoThread)
self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread
wfmoThread.start()
def processEnded(self, processHandle, processHandleKey):
wfmoThread = self.phandleKeyToThreadHandle[processHandleKey]
processTransport = self.phandleToTransport[processHandle]
self.threadToNumEnded[wfmoThread] += 1
# Decrement proc handle count for thread
self.threadToNumProcessHandles[wfmoThread] -= 1
# If we go from 63 to 62 phandles for the thread, mark it available.
if self.threadToNumProcessHandles[wfmoThread] == 62:
self.availableThreads.append(wfmoThread)
self.usedThreads.remove(wfmoThread)
# If we go to 0 phandles, end the thread
elif self.threadToNumProcessHandles[wfmoThread] == 0:
# Mark thread as unavailable
self.availableThreads.remove(wfmoThread)
# Notify the thread that it should exit.
if not self.threadToMsgWindowCreated[wfmoThread]:
val = WaitForSingleObject(self.threadToMsgWindowCreationEvent[wfmoThread], INFINITE)
if val != WAIT_OBJECT_0:
raise RuntimeError("WaitForSingleObject returned %d. It should only return %d" % (val, WAIT_OBJECT_0))
# Notify the thread that it should wait on the process handle.
win32api.PostMessage(
self.threadToMsgWindow[wfmoThread], # thread id
WM_CLOSE_THREAD, # message
0, # wParam
0 # lParam
)
# Cleanup thread resources
del self.threadToNumProcessHandles[wfmoThread]
del self.threadToMsgWindowCreated[wfmoThread]
#del self.wfmoThread
# Cleanup process handle resources
del self.needWaiting[processHandleKey]
del self.phandleToTransport[processHandle]
# Call the transport's processEnded method
processTransport.processEnded()
def checkWork(self):
if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
return 0
exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
if exitCode == 0:
err = error.ProcessDone(exitCode)
else:
err = error.ProcessTerminated(exitCode)
self.deactivate()
self.proc.protocol.processEnded(failure.Failure(err))
return 0
def TestExplorerEvents():
iexplore = win32com.client.DispatchWithEvents(
"InternetExplorer.Application", ExplorerEvents)
thread = win32api.GetCurrentThreadId()
print 'TestExplorerEvents created IE object on thread %d'%thread
iexplore.Visible = 1
try:
iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
except pythoncom.com_error, details:
print "Warning - could not open the test HTML file", details
# In this free-threaded example, we can simply wait until an event has
# been set - we will give it 2 seconds before giving up.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print "Document load event FAILED to fire!!!"
iexplore.Quit()
# Now we can do the same thing to wait for exit!
# Although Quit generates events, in this free-threaded world we
# do *not* need to run any message pumps.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print "OnQuit event FAILED to fire!!!"
iexplore = None
print "Finished the IE event sample!"
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.log('start')
self.start()
self.log('wait')
win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
self.log('done')
except Exception, x:
self.log('Exception : %s' % x)
self.SvcStop()
def TestExplorerEvents():
iexplore = win32com.client.DispatchWithEvents(
"InternetExplorer.Application", ExplorerEvents)
thread = win32api.GetCurrentThreadId()
print 'TestExplorerEvents created IE object on thread %d'%thread
iexplore.Visible = 1
try:
iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
except pythoncom.com_error, details:
print "Warning - could not open the test HTML file", details
# In this free-threaded example, we can simply wait until an event has
# been set - we will give it 2 seconds before giving up.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print "Document load event FAILED to fire!!!"
iexplore.Quit()
# Now we can do the same thing to wait for exit!
# Although Quit generates events, in this free-threaded world we
# do *not* need to run any message pumps.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print "OnQuit event FAILED to fire!!!"
iexplore = None
print "Finished the IE event sample!"
def SvcDoRun(self):
# Redirect stdout and stderr to prevent "IOError: [Errno 9]
# Bad file descriptor". Windows services don't have functional
# output streams.
sys.stdout = sys.stderr = open('nul', 'w')
# Write a 'started' event to the event log...
win32evtlogutil.ReportEvent(self._svc_display_name_,
servicemanager.PYS_SERVICE_STARTED,
0, # category
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, ''))
print("Begin: %s" % (self._svc_display_name_))
hostport = ':8888'
print('Starting py.execnet SocketServer on %s' % hostport)
serversock = socketserver.bind_and_listen(hostport)
thread = threading.Thread(
target=socketserver.startserver,
args=(serversock,),
kwargs={'loop': True})
thread.setDaemon(True)
thread.start()
# wait to be stopped or self.WAIT_TIME to pass
while True:
result = win32event.WaitForSingleObject(
self.hWaitStop, self.WAIT_TIME)
if result == win32event.WAIT_OBJECT_0:
break
# write a 'stopped' event to the event log.
win32evtlogutil.ReportEvent(self._svc_display_name_,
servicemanager.PYS_SERVICE_STOPPED,
0, # category
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, ''))
print("End: %s" % appname)
def wait(self, timeout=None):
"""Wait until the child exits. If timeout is not specified this
blocks indefinately. Otherwise, timeout specifies the number of
seconds to wait."""
if self.exitstatus is not None:
return
if timeout is None:
timeout = INFINITE
else:
timeout = 1000 * timeout
ret = WaitForSingleObject(self.child_handle, timeout)
if ret == WAIT_TIMEOUT:
raise TIMEOUT, 'Timeout exceeded in wait().'
self.exitstatus = GetExitCodeProcess(self.child_handle)
return self.exitstatus
def isalive(self):
"""Return True if the child is alive, False otherwise."""
if self.exitstatus is not None:
return False
ret = WaitForSingleObject(self.child_handle, 0)
if ret == WAIT_OBJECT_0:
self.exitstatus = GetExitCodeProcess(self.child_handle)
return False
return True
def notifyOnExit(self, processHandle, processTransport):
processHandleKey = self.phandleToPhandleKey[processHandle]
# If there are available threads, use one of them
if len(self.availableThreads) > 0:
wfmoThread = self.availableThreads[0]
self.threadToNumProcessHandles[wfmoThread] += 1
self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread
# Update used/available thread lists
if self.threadToNumProcessHandles[wfmoThread] == 63:
self.usedThreads.append(wfmoThread)
self.availableThreads.remove(wfmoThread)
# Make sure the message window has been created so
# we can send messages to the thread.
if self.threadToMsgWindowCreated[wfmoThread] is False:
val = WaitForSingleObject(self.threadToMsgWindowCreationEvent[wfmoThread], INFINITE)
if val != WAIT_OBJECT_0:
raise RuntimeError("WaitForSingleObject returned %d. It should only return %d" % (val, WAIT_OBJECT_0))
# Notify the thread that it should wait on the process handle.
if win32api.PostMessage(
self.threadToMsgWindow[wfmoThread],
WM_NEW_PHANDLE, # message
processHandleKey, # wParam
0 # lParam
) == 0:
raise Exception("Failed to post thread message!")
else:
# Create a new thread and wait on the proc handle
wfmoThread = threading.Thread(
target=self.doWaitForProcessExit,
args=(processHandleKey,),
name="iocpreactor.process_waiter.ProcessWaiter.waitForProcessExit pid=%d" % self.realPid)
# Create a window creation event that will be triggered from the thread
self.threadToMsgWindowCreationEvent[wfmoThread] = CreateEvent(None, 0, 0, None)
self.threadToMsgWindowCreated[wfmoThread] = False
self.threadToNumProcessHandles[wfmoThread] = 1
self.availableThreads.append(wfmoThread)
self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread
wfmoThread.start()
def processEnded(self, processHandle, processHandleKey):
wfmoThread = self.phandleKeyToThreadHandle[processHandleKey]
processTransport = self.phandleToTransport[processHandle]
self.threadToNumEnded[wfmoThread] += 1
# Decrement proc handle count for thread
self.threadToNumProcessHandles[wfmoThread] -= 1
# If we go from 63 to 62 phandles for the thread, mark it available.
if self.threadToNumProcessHandles[wfmoThread] == 62:
self.availableThreads.append(wfmoThread)
self.usedThreads.remove(wfmoThread)
# If we go to 0 phandles, end the thread
elif self.threadToNumProcessHandles[wfmoThread] == 0:
# Mark thread as unavailable
self.availableThreads.remove(wfmoThread)
# Notify the thread that it should exit.
if not self.threadToMsgWindowCreated[wfmoThread]:
val = WaitForSingleObject(self.threadToMsgWindowCreationEvent[wfmoThread], INFINITE)
if val != WAIT_OBJECT_0:
raise RuntimeError("WaitForSingleObject returned %d. It should only return %d" % (val, WAIT_OBJECT_0))
# Notify the thread that it should wait on the process handle.
win32api.PostMessage(
self.threadToMsgWindow[wfmoThread], # thread id
WM_CLOSE_THREAD, # message
0, # wParam
0 # lParam
)
# Cleanup thread resources
del self.threadToNumProcessHandles[wfmoThread]
del self.threadToMsgWindowCreated[wfmoThread]
#del self.wfmoThread
# Cleanup process handle resources
del self.needWaiting[processHandleKey]
del self.phandleToTransport[processHandle]
# Call the transport's processEnded method
processTransport.processEnded()
def checkWork(self):
if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
return 0
exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
if exitCode == 0:
err = error.ProcessDone(exitCode)
else:
err = error.ProcessTerminated(exitCode)
self.deactivate()
self.proc.protocol.processEnded(failure.Failure(err))
return 0
def wait_for_elevated_process(process_info):
if platform.system() == 'Windows' and 'hProcess' in process_info:
import win32api
import win32con
import win32event
import win32process
win32event.WaitForSingleObject(process_info['hProcess'], 600000)
ret = win32process.GetExitCodeProcess(process_info['hProcess'])
win32api.CloseHandle(process_info['hProcess'])
return ret
# pylint: enable=E0611,E0401
# pylint: disable=E1101
def acquire(self):
win32event.WaitForSingleObject(self.handle, win32event.INFINITE)
self.locked = True
def connect_pipe(pipe, pipeName):
overLap = pywintypes.OVERLAPPED()
overLap.hEvent = win32event.CreateEvent(None, 1, 0, None)
if overLap.hEvent == 0:
raise PipeError('Could not create hEvent')
try:
# Wait for a pipe client connection
ret = win32pipe.ConnectNamedPipe(pipe, overLap)
if not ret in (0, ERROR_PIPE_CONNECTED):
if ret == ERROR_IO_PENDING:
ret = win32event.WaitForSingleObject(overLap.hEvent,
1000 * CONNECT_TIMEOUT_SECS)
if ret != win32event.WAIT_OBJECT_0:
# Timeout error
raise PipeError('Timeout error')
else:
# API error
raise PipeError('API error')
ret = win32pipe.GetOverlappedResult(pipe, overLap, True)
if not ret in (0, ERROR_PIPE_CONNECTED):
# API Error
raise PipeError('API error 2')
except PipeError:
# Named pipe exception
win32file.CancelIo(pipe)
pipe.close()
raise
except BaseException, err:
win32file.CancelIo(pipe)
pipe.close()
pipe = None
raise PipeError('BaseException : ' + str(err))
return pipe
def testRecord(self):
d = ds.DirectSoundCaptureCreate(None, None)
sdesc = ds.DSCBUFFERDESC()
sdesc.dwBufferBytes = 352800 # 2 seconds
sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX()
sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM
sdesc.lpwfxFormat.nChannels = 2
sdesc.lpwfxFormat.nSamplesPerSec = 44100
sdesc.lpwfxFormat.nAvgBytesPerSec = 176400
sdesc.lpwfxFormat.nBlockAlign = 4
sdesc.lpwfxFormat.wBitsPerSample = 16
buffer = d.CreateCaptureBuffer(sdesc)
event = win32event.CreateEvent(None, 0, 0, None)
notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify)
notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event))
buffer.Start(0)
win32event.WaitForSingleObject(event, -1)
event.Close()
data = buffer.Update(0, 352800)
fname=os.path.join(win32api.GetTempPath(), 'test_directsound_record.wav')
f = open(fname, 'wb')
f.write(wav_header_pack(sdesc.lpwfxFormat, 352800))
f.write(data)
f.close()
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def Connect(entryName, bUseCallback):
if bUseCallback:
theCallback = Callback
win32event.ResetEvent(callbackEvent)
else:
theCallback = None
# in order to *use* the username/password of a particular dun entry, one must
# explicitly get those params under win95....
try:
dp, b = win32ras.GetEntryDialParams( None, entryName )
except:
print "Couldn't find DUN entry: %s" % entryName
else:
hras, rc = win32ras.Dial(None, None, (entryName, "", "", dp[ 3 ], dp[ 4 ], ""),theCallback)
# hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
# print hras, rc
if not bUseCallback and rc != 0:
print "Could not dial the RAS connection:", win32ras.GetErrorString(rc)
hras = HangUp( hras )
# don't wait here if there's no need to....
elif bUseCallback and win32event.WaitForSingleObject(callbackEvent, 60000)!=win32event.WAIT_OBJECT_0:
print "Gave up waiting for the process to complete!"
# sdk docs state one must explcitly hangup, even if there's an error....
try:
cs = win32ras.GetConnectStatus( hras )
except:
# on error, attempt a hang up anyway....
hras = HangUp( hras )
else:
if int( cs[ 0 ] ) == win32ras.RASCS_Disconnected:
hras = HangUp( hras )
return hras, rc
def SvcDoRun(self):
# do nothing at all - just wait to be stopped
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
# Write a stop message.
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, '')
)