def serialWriteEvent(self):
try:
dataToWrite = self.outQueue.pop(0)
except IndexError:
self.writeInProgress = 0
return
else:
win32file.WriteFile(self._serial.hComPort, dataToWrite, self._overlappedWrite)
python类WriteFile()的实例源码
def write(self, offset, data):
win32file.SetFilePointer(self.fhandle, offset, 0)
# The WinPmem driver returns bytes_written == 0 always. This is probably
# a bug in its write routine, so we ignore it here. If the operation was
# successful we assume all bytes were written.
err, _bytes_written = win32file.WriteFile(self.fhandle, data)
if err == 0:
return len(data)
return 0
def send(self, input):
if not self.stdin:
return None
try:
x = msvcrt.get_osfhandle(self.stdin.fileno())
(errCode, written) = WriteFile(x, input)
except ValueError:
return self._close('stdin')
except (subprocess.pywintypes.error, Exception), why:
if why[0] in (109, errno.ESHUTDOWN):
return self._close('stdin')
raise
return written
def write_text(self, text):
" Write text to the stdin of the process. "
win32file.WriteFile(self.stdin_handle, text.encode('utf-8'))
def write(self, string):
win32file.WriteFile(self.Fd, string)
def run(self):
import win32file
self.file_handle = win32file.CreateFile(self.named_pipe_path,
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0, None,
win32file.OPEN_EXISTING,
0, None)
log.info('Windows named pipe connected')
self.fire_connected()
while True:
# The following code is cleaner, than waiting for an exception while writing to detect pipe closing,
# but causes mpv to hang and crash while closing when closed at the wrong time.
# if win32file.GetFileAttributes(self.named_pipe_path) != win32file.FILE_ATTRIBUTE_NORMAL:
# # pipe was closed
# break
try:
while not self.write_queue.empty():
win32file.WriteFile(self.file_handle, self.write_queue.get_nowait())
except win32file.error:
log.warning('Exception while writing to Windows named pipe. Assuming pipe closed.')
break
size = win32file.GetFileSize(self.file_handle)
if size > 0:
while size > 0:
# pipe has data to read
data = win32file.ReadFile(self.file_handle, 512)
self.on_data(data[1])
size = win32file.GetFileSize(self.file_handle)
else:
time.sleep(1)
log.info('Windows named pipe closed')
win32file.CloseHandle(self.file_handle)
self.file_handle = None
self.fire_disconnected()
def send(self, input):
if not self.stdin:
return None
try:
x = msvcrt.get_osfhandle(self.stdin.fileno())
(errCode, written) = WriteFile(x, input)
except ValueError:
print("close stdin")
return self._close('stdin')
except (subprocess.pywintypes.error, Exception) as why:
if why[0] in (109, errno.ESHUTDOWN):
print("close stdin")
return self._close('stdin')
raise
return written
def write_mbr_winapi( _file ):
print 'Are you SURE you want to overwrite the MBR?? This will possibly make the volume unbootable.'
response = raw_input( 'Type \"YES\" then Return to continue, anything else then Return to not continue:' )
if response != 'YES':
return
h = None
handles = []
try:
for x in range( num_mbr_handles ):
h = win32file.CreateFile( '\\\\.\\PhysicalDrive0',
win32con.GENERIC_WRITE,
win32file.FILE_SHARE_WRITE,
None,
win32file.OPEN_EXISTING,
win32file.FILE_ATTRIBUTE_NORMAL,
None )
if ( h != win32file.INVALID_HANDLE_VALUE ):
handles.append( h )
f = open( _file, 'rb' )
if f <> None:
fsize = os.path.getsize( _file )
wsize = 512
if fsize > 512:
print 'WARNING: File being written is > 512 bytes, will only write 512...'
wsize = 512
contents = f.read( fsize )
if fsize < 512:
print 'WARNING: Padding file up to 512 bytes, may not have expected results...'
## pad it out to 512 bytes
diff = 512 - 512
for num in xrange( diff ):
contents += 'A'
win32file.WriteFile( h, contents, None )
f.close()
except Exception, e:
print str( e )
print '\tAre you running as Administrator?'
for handle in handles:
win32file.CloseHandle( handle )
#############
def _stub(cmd_name, stdin_name, stdout_name, stderr_name):
"""INTERNAL: Stub process that will start up the child process."""
# Open the 4 pipes (command, stdin, stdout, stderr)
cmd_pipe = CreateFile(cmd_name, GENERIC_READ|GENERIC_WRITE, 0, None,
OPEN_EXISTING, 0, None)
SetHandleInformation(cmd_pipe, HANDLE_FLAG_INHERIT, 1)
stdin_pipe = CreateFile(stdin_name, GENERIC_READ, 0, None,
OPEN_EXISTING, 0, None)
SetHandleInformation(stdin_pipe, HANDLE_FLAG_INHERIT, 1)
stdout_pipe = CreateFile(stdout_name, GENERIC_WRITE, 0, None,
OPEN_EXISTING, 0, None)
SetHandleInformation(stdout_pipe, HANDLE_FLAG_INHERIT, 1)
stderr_pipe = CreateFile(stderr_name, GENERIC_WRITE, 0, None,
OPEN_EXISTING, 0, None)
SetHandleInformation(stderr_pipe, HANDLE_FLAG_INHERIT, 1)
# Learn what we need to do..
header = _read_header(cmd_pipe)
input = _parse_header(header)
if 'command' not in input or 'args' not in input:
ExitProcess(2)
# http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx
startupinfo = STARTUPINFO()
startupinfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
startupinfo.hStdInput = stdin_pipe
startupinfo.hStdOutput = stdout_pipe
startupinfo.hStdError = stderr_pipe
startupinfo.wShowWindow = SW_HIDE
# Grant access so that our parent can open its grandchild.
if 'parent_sid' in input:
mysid = _get_current_sid()
parent = ConvertStringSidToSid(input['parent_sid'])
sattrs = _create_security_attributes(mysid, parent,
access=PROCESS_ALL_ACCESS)
else:
sattrs = None
try:
res = CreateProcess(input['command'], input['args'], sattrs, None,
True, CREATE_NEW_CONSOLE, os.environ, os.getcwd(),
startupinfo)
except WindowsError, e:
message = _quote_header(str(e))
WriteFile(cmd_pipe, 'status=error\nmessage=%s\n\n' % message)
ExitProcess(3)
else:
pid = res[2]
# Pass back results and exit
err, nbytes = WriteFile(cmd_pipe, 'status=ok\npid=%s\n\n' % pid)
ExitProcess(0)
def SpoolWorker(srcHandle, destHandle, outFiles, doneEvent):
"""Thread entry point for implementation of MakeSpyPipe"""
try:
buffer = win32file.AllocateReadBuffer(SPOOL_BYTES)
while 1:
try:
#print >> SPOOL_ERROR, "Calling ReadFile..."; SPOOL_ERROR.flush()
hr, data = win32file.ReadFile(srcHandle, buffer)
#print >> SPOOL_ERROR, "ReadFile returned '%s', '%s'" % (str(hr), str(data)); SPOOL_ERROR.flush()
if hr != 0:
raise Exception("win32file.ReadFile returned %i, '%s'" % (hr, data))
elif len(data) == 0:
break
except pywintypes.error, e:
#print >> SPOOL_ERROR, "ReadFile threw '%s'" % str(e); SPOOL_ERROR.flush()
if e.args[0] == winerror.ERROR_BROKEN_PIPE:
break
else:
raise e
#print >> SPOOL_ERROR, "Writing to %i file objects..." % len(outFiles); SPOOL_ERROR.flush()
for f in outFiles:
f.write(data)
#print >> SPOOL_ERROR, "Done writing to file objects."; SPOOL_ERROR.flush()
#print >> SPOOL_ERROR, "Writing to destination %s" % str(destHandle); SPOOL_ERROR.flush()
if destHandle:
#print >> SPOOL_ERROR, "Calling WriteFile..."; SPOOL_ERROR.flush()
hr, bytes = win32file.WriteFile(destHandle, data)
#print >> SPOOL_ERROR, "WriteFile() passed %i bytes and returned %i, %i" % (len(data), hr, bytes); SPOOL_ERROR.flush()
if hr != 0 or bytes != len(data):
raise Exception("win32file.WriteFile() passed %i bytes and returned %i, %i" % (len(data), hr, bytes))
srcHandle.Close()
if doneEvent:
win32event.SetEvent(doneEvent)
if destHandle:
destHandle.Close()
except:
info = sys.exc_info()
SPOOL_ERROR.writelines(apply(traceback.format_exception, info), '')
SPOOL_ERROR.flush()
del info