本文整理汇总了Python中msvcrt.get_osfhandle函数的典型用法代码示例。如果您正苦于以下问题:Python get_osfhandle函数的具体用法?Python get_osfhandle怎么用?Python get_osfhandle使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_osfhandle函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _mk_inheritable
def _mk_inheritable(fd):
if version >= (3, 3):
if sys.platform == 'win32':
# Change to Windwos file handle
import msvcrt
fdh = msvcrt.get_osfhandle(fd)
os.set_handle_inheritable(fdh, True)
return fdh
else:
os.set_inheritable(fd, True)
return fd
elif sys.platform == 'win32':
# TODO: find a hack??
# Not yet working
import msvcrt
import _subprocess
curproc = _subprocess.GetCurrentProcess()
fdh = msvcrt.get_osfhandle(fd)
fdh = _subprocess.DuplicateHandle(
curproc, fdh, curproc, 0,
True, # set inheritable FLAG
_subprocess.DUPLICATE_SAME_ACCESS)
return fdh
else:
return fd
示例2: _checkFileObjInheritable
def _checkFileObjInheritable(cls, fileobj, handle_name):
"""Check if a given file-like object (or whatever else subprocess.Popen
takes as a handle/stream) can be correctly inherited by a child process.
This just duplicates the code in subprocess.Popen._get_handles to make
sure we go down the correct code path; this to catch some non-standard
corner cases."""
import _subprocess
import ctypes
import msvcrt
new_handle = None
try:
if fileobj is None:
handle = _subprocess.GetStdHandle(getattr(_subprocess,
handle_name))
if handle is None:
return True # No need to check things we create
elif fileobj == subprocess.PIPE:
return True # No need to check things we create
elif isinstance(fileobj, int):
handle = msvcrt.get_osfhandle(fileobj)
else:
# Assuming file-like object
handle = msvcrt.get_osfhandle(fileobj.fileno())
new_handle = self._make_inheritable(handle)
return True
except:
return False
finally:
CloseHandle = ctypes.windll.kernel32.CloseHandle
if new_handle is not None:
CloseHandle(new_handle)
示例3: read_bytes
def read_bytes(self, buffer_size=4096):
out = self.popen.stdout
if POSIX:
while True:
i, _, _ = select.select([out], [], [])
if i:
return out.read(buffer_size)
else:
import ctypes
import msvcrt
kernel32 = ctypes.windll.kernel32
buffer_size = 1
bytes_read = bytearray()
#wait for some output synchronously, to not cause infinite loop
bytes_read.extend(out.read(buffer_size))
#read until end of current output
kernel32.SetNamedPipeHandleState(ctypes.c_void_p(msvcrt.get_osfhandle(out.fileno())), ctypes.byref(ctypes.c_int(1)), None, None)
#'Invalid Argument' means that there are no more bytes left to read
while True:
try:
cur_bytes_read=out.read(buffer_size)
if not cur_bytes_read:
break
bytes_read.extend(cur_bytes_read)
except (OSError, IOError):
break
kernel32.SetNamedPipeHandleState(ctypes.c_void_p(msvcrt.get_osfhandle(out.fileno())), ctypes.byref(ctypes.c_int(0)), None, None)
# f'in HACK, for \r\n -> \n translation on windows
# I tried universal_endlines but it was pain and misery! :'(
return bytes_read.replace(b'\r\n', b'\n')
示例4: _create_tmp_files
def _create_tmp_files(env=None):
dirname = None
if env is None:
env = os.environ
for env_var_name in 'TMPDIR', 'TEMP', 'TMP':
if env.has_key(env_var_name):
dirname = env[env_var_name]
if dirname and os.path.exists(dirname):
break
if dirname is None:
for dirname2 in r'c:\temp', r'c:\tmp', r'\temp', r'\tmp':
try:
os.makedirs(dirname2)
dirname = dirname2
break
except:
pass
if dirname is None:
raise Exception('Unable to create temp dir. Insufficient access rights.')
out_file = tempfile.TemporaryFile(mode="r+b", dir=dirname)
err_file = tempfile.TemporaryFile(mode="r+b", dir=dirname)
return (msvcrt.get_osfhandle(out_file.fileno()),
msvcrt.get_osfhandle(err_file.fileno()),
out_file,
err_file)
示例5: __init__
def __init__( self, *args, **kwargs ):
"""
Both output streams stdout and stderr can be set to any object
that has a write function. Leaving stdout or stderr out will
redirect both streams to their system equivalent (sys.stdout and
sys.stderr).
"""
self._bypass_stdout = False
self._bypass_stderr = False
if 'stdout' in kwargs and not kwargs['stdout'] is subprocess.PIPE:
self._stdout_file = kwargs['stdout']
kwargs['stdout'] = subprocess.PIPE
self._bypass_stdout = True
elif not 'stdout' in kwargs:
self._stdout_file = sys.stdout
kwargs['stdout'] = subprocess.PIPE
self._bypass_stdout = True
if 'stderr' in kwargs and not kwargs['stderr'] is subprocess.PIPE:
self._stderr_file = kwargs['stderr']
kwargs['stderr'] = subprocess.PIPE
self._bypass_stderr = True
elif not 'stderr' in kwargs:
self._stderr_file = sys.stderr
kwargs['stderr'] = subprocess.PIPE
self._bypass_stderr = True
subprocess.Popen.__init__( self, *args, **kwargs )
if self._bypass_stdout:
self._stdout_hdl = msvcrt.get_osfhandle( self.stdout.fileno() )
if self._bypass_stderr:
self._stderr_hdl = msvcrt.get_osfhandle( self.stderr.fileno() )
示例6: _create_tmp_files
def _create_tmp_files():
out_file = tempfile.TemporaryFile(mode="r+b")
err_file = tempfile.TemporaryFile(mode="r+b")
return (msvcrt.get_osfhandle(out_file.fileno()),
msvcrt.get_osfhandle(err_file.fileno()),
out_file,
err_file)
示例7: __init__
def __init__ (self, executable, args, env, logfile=None):
self.logfile = logfile
self.executable = find_executable(executable)
self.args = args
self.exitstatus = None
self.running = 0
tempfile.template = None
if logfile:
fd = os.open(logfile.filename,
O_WRONLY | O_CREAT | O_APPEND, 0664)
# Get the NT handle for fd
hStdout = msvcrt.get_osfhandle(fd)
# Equivalent of os.dup() except for Win32 HANDLE's
hStderr = win32api.DuplicateHandle(hStdout)
else:
# Grab the HANDLE's for current stdout & stderr
hStdout = msvcrt.get_osfhandle(sys.stdout)
hStderr = msvcrt.get_osfhandle(sys.stderr)
# Grab the HANDLE for stdin
hStdin = msvcrt.get_osfhandle(sys.stdin)
for key in env.keys():
os.environ[key] = env[key]
if logfile:
output = fd
else:
output = sys.stderr
output.write("executable is " +
str(self.executable) +
", args are " +
str(args) + ", env = " +
str(os.environ) + "\n")
# Create the process
# All of this footwork, should allow this sucker to run from a console, or GUI app.
sCmdLine = self.executable
for arg in args:
sCmdLine = sCmdLine + " " + arg
StartupInfo = win32process.STARTUPINFO()
StartupInfo.dwFlags = win32con.STARTF_USESTDHANDLES | win32con.STARTF_USESHOWWINDOW
StartupInfo.hStdInput = hStdin
StartupInfo.hStdOutput = hStdout
StartupInfo.hStdError = hStderr
StartupInfo.wShowWindow = win32con.SW_HIDE
hProcess, hThread, dwPid, dwTid = win32api.CreateProcess(self.executable,
sCmdLine,
None,
None,
0,
win32process.CREATE_NEW_CONSOLE,
None,
None,
StartupInfo)
win32api.CloseHandle(hThread)
self.pid = dwPid
self.hProcess = hProcess
self.running = 1
add_exit_function(lambda x=self: x.kill())
示例8: __init__
def __init__(self, incoming, outgoing):
import msvcrt
self._keepalive = (incoming, outgoing)
if hasattr(incoming, "fileno"):
self._fileno = incoming.fileno()
incoming = msvcrt.get_osfhandle(incoming.fileno())
if hasattr(outgoing, "fileno"):
outgoing = msvcrt.get_osfhandle(outgoing.fileno())
self.incoming = incoming
self.outgoing = outgoing
示例9: _isFileObjInheritable
def _isFileObjInheritable(cls, fileobj, stream_name):
"""Check if a given file-like object (or whatever else subprocess.Popen
takes as a handle/stream) can be correctly inherited by a child process.
This just duplicates the code in subprocess.Popen._get_handles to make
sure we go down the correct code path; this to catch some non-standard
corner cases.
@param fileobj The object being used as a fd/handle/whatever
@param stream_name The name of the stream, "stdin", "stdout", or "stderr"
"""
import _subprocess
import ctypes
import msvcrt
new_handle = None
# Things that we know how to reset (i.e. not custom fds)
valid_list = {
"stdin": (sys.stdin, sys.__stdin__, 0),
"stdout": (sys.stdout, sys.__stdout__, 1),
"stderr": (sys.stderr, sys.__stderr__, 2),
}[stream_name]
try:
if fileobj is None:
std_handle = {
"stdin": _subprocess.STD_INPUT_HANDLE,
"stdout": _subprocess.STD_OUTPUT_HANDLE,
"stderr": _subprocess.STD_ERROR_HANDLE,
}[stream_name]
handle = _subprocess.GetStdHandle(std_handle)
if handle is None:
# subprocess.Popen._get_handles creates a new pipe here
# we don't have to worry about things we create
return True
elif fileobj == subprocess.PIPE:
# We're creating a new pipe; newly created things are inheritable
return True
elif fileobj not in valid_list:
# We are trying to use a custom fd; don't do anything fancy here,
# we don't want to actually use subprocess.PIPE
return True
elif isinstance(fileobj, int):
handle = msvcrt.get_osfhandle(fileobj)
else:
# Assuming file-like object
handle = msvcrt.get_osfhandle(fileobj.fileno())
new_handle = self._make_inheritable(handle)
return True
except:
return False
finally:
CloseHandle = ctypes.windll.kernel32.CloseHandle
if new_handle is not None:
CloseHandle(new_handle)
示例10: _get_handles
def _get_handles(self, stdin, stdout, stderr):
if stdin is None and stdout is None and stderr is None:
return (-1, -1, -1, -1, -1, -1)
(p2cread, p2cwrite) = (-1, -1)
(c2pread, c2pwrite) = (-1, -1)
(errread, errwrite) = (-1, -1)
if stdin is None:
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
(p2cread, _) = _winapi.CreatePipe(None, 0)
p2cread = Handle(p2cread)
_winapi.CloseHandle(_)
elif stdin == PIPE:
(p2cread, p2cwrite) = _winapi.CreatePipe(None, 0)
(p2cread, p2cwrite) = (Handle(p2cread), Handle(p2cwrite))
elif stdin == DEVNULL:
p2cread = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdin, int):
p2cread = msvcrt.get_osfhandle(stdin)
else:
p2cread = msvcrt.get_osfhandle(stdin.fileno())
p2cread = self._make_inheritable(p2cread)
if stdout is None:
c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
(_, c2pwrite) = _winapi.CreatePipe(None, 0)
c2pwrite = Handle(c2pwrite)
_winapi.CloseHandle(_)
elif stdout == PIPE:
(c2pread, c2pwrite) = _winapi.CreatePipe(None, 0)
(c2pread, c2pwrite) = (Handle(c2pread), Handle(c2pwrite))
elif stdout == DEVNULL:
c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdout, int):
c2pwrite = msvcrt.get_osfhandle(stdout)
else:
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
c2pwrite = self._make_inheritable(c2pwrite)
if stderr is None:
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
(_, errwrite) = _winapi.CreatePipe(None, 0)
errwrite = Handle(errwrite)
_winapi.CloseHandle(_)
elif stderr == PIPE:
(errread, errwrite) = _winapi.CreatePipe(None, 0)
(errread, errwrite) = (Handle(errread), Handle(errwrite))
elif stderr == STDOUT:
errwrite = c2pwrite
elif stderr == DEVNULL:
errwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stderr, int):
errwrite = msvcrt.get_osfhandle(stderr)
else:
errwrite = msvcrt.get_osfhandle(stderr.fileno())
errwrite = self._make_inheritable(errwrite)
return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
示例11: recv_multi_impl
def recv_multi_impl(conns, maxsize, timeout):
"""Reads from the first available pipe.
If timeout is None, it's blocking. If timeout is 0, it is not blocking.
"""
# TODO(maruel): Use WaitForMultipleObjects(). Python creates anonymous pipes
# for proc.stdout and proc.stderr but they are implemented as named pipes on
# Windows. Since named pipes are not waitable object, they can't be passed
# as-is to WFMO(). So this means N times CreateEvent(), N times ReadFile()
# and finally WFMO(). This requires caching the events handles in the Popen
# object and remembering the pending ReadFile() calls. This will require
# some re-architecture to store the relevant event handle and OVERLAPPEDIO
# object in Popen or the file object.
maxsize = max(maxsize or 16384, 1)
if timeout:
start = time.time()
handles = [
(i, msvcrt.get_osfhandle(c.fileno())) for i, c in enumerate(conns)
]
while handles:
for index, handle in handles:
try:
avail = min(PeekNamedPipe(handle), maxsize)
if avail:
return index, ReadFile(handle, avail)[1]
if (timeout and (time.time() - start) >= timeout) or timeout == 0:
return None, None
# Polling rocks.
time.sleep(0.001)
except OSError:
handles.remove((index, handle))
break
# Nothing to wait for.
return None, None
示例12: unlock
def unlock(file):
hfile = msvcrt.get_osfhandle(file.fileno())
overlapped = OVERLAPPED()
if UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped)):
return True
else:
return False
示例13: readpipeNONBLK
def readpipeNONBLK(self, cmdpipe):
#
# Don't block waiting for output to appear, just grab
# whatever is available now on the pipe. fstat on
# bsd unix pipes gives the available-to-read count.
# But doesn't work on linux, or on win32 CreatePipe
# anonymous pipes (purportedly works on win32 posix pipes).
#
bytes = ""
try:
# anything available to read right now?
nAvail = 0
x = cmdpipe.fileno()
if subprocess.mswindows:
h = msvcrt.get_osfhandle(x)
dword = ctypes.c_ulong()
rc = ctypes.windll.kernel32.PeekNamedPipe(
h, None, 0, None, ctypes.byref(dword), None
)
if rc:
nAvail = int(dword.value)
else:
#unix
# unfortunately, the os.fstat trick doesn't work on linux
# nAvail = os.fstat(x).st_size
# whereas the select "poll" seems to work on all *nix
if select.select([cmdpipe], [], [], 0)[0]:
nAvail = 262144
if nAvail > 0:
bytes = os.read(x,nAvail)
except Exception:
pass
return bytes
示例14: _check_ready
def _check_ready(self, conn, maxsize=1024):
if maxsize < 1:
maxsize = 1
if conn is None:
return
try:
x = msvcrt.get_osfhandle(conn.fileno())
(read, nAvail, nMessage) = PeekNamedPipe(x, 0)
if maxsize < nAvail:
nAvail = maxsize
if nAvail > 0:
if conn is self.stdout:
self.emit('stdout-ready')
elif conn is self.stderr:
self.emit('stderr-ready')
except ValueError:
return conn.close()
except (WindowsError, Exception) as ex:
if ex[0] in (109, errno.ESHUTDOWN):
return conn.close()
raise
return True
示例15: _connect_stdio
def _connect_stdio(self):
if os.name == 'nt':
pipe = PipeHandle(msvcrt.get_osfhandle(sys.stdin.fileno()))
else:
pipe = sys.stdin
coroutine = self._loop.connect_read_pipe(self._fact, pipe)
self._loop.run_until_complete(coroutine)
debug("native stdin connection successful")
if os.name == 'nt':
pipe = PipeHandle(msvcrt.get_osfhandle(sys.stdout.fileno()))
else:
pipe = sys.stdout
coroutine = self._loop.connect_write_pipe(self._fact, pipe)
self._loop.run_until_complete(coroutine)
debug("native stdout connection successful")