def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwargs):
self.stdin = self.stdout = self.stderr = None
stdin_rh = stdin_wh = stdout_rh = stdout_wh = stderr_rh = stderr_wh = None
if stdin == subprocess.PIPE:
stdin_rh, stdin_wh = pipe()
stdin_rfd = msvcrt.open_osfhandle(stdin_rh.Detach(), os.O_RDONLY)
self.stdin_rh = stdin_rh
else:
stdin_rfd = stdin
self.stdin_rh = None
if stdout == subprocess.PIPE:
stdout_rh, stdout_wh = pipe()
stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
else:
stdout_wfd = stdout
if stderr == subprocess.PIPE:
stderr_rh, stderr_wh = pipe()
stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
elif stderr == subprocess.STDOUT:
stderr_wfd = stdout_wfd
else:
stderr_wfd = stderr
try:
super(Popen, self).__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
stderr=stderr_wfd, **kwargs)
except:
for handle in (stdin_rh, stdin_wh, stdout_rh, stdout_wh, stderr_rh, stderr_wh):
if handle is not None:
win32file.CloseHandle(handle)
raise
else:
if stdin_wh is not None:
self.stdin = AsyncFile(stdin_wh, mode='w')
if stdout_rh is not None:
self.stdout = AsyncFile(stdout_rh, mode='r')
if stderr_rh is not None:
self.stderr = AsyncFile(stderr_rh, mode='r')
finally:
if stdin == subprocess.PIPE:
os.close(stdin_rfd)
if stdout == subprocess.PIPE:
os.close(stdout_wfd)
if stderr == subprocess.PIPE:
os.close(stderr_wfd)
python类CloseHandle()的实例源码
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 )
#############