我知道sys.stdout
是一个Python object that wraps the output file handle,但我想知道这些文件句柄是否“同步”并且总是相同的
例如,假设sys.stdout.isatty()
是真的。我调用^{sys.stdout
?我的代码使用了^{sys.stdout.isatty
,那就太好了
下面是一个示例(我目前无法访问windows计算机,但希望代码是正确的)。在有重定向和无重定向的情况下运行(或在对^{
import sys
from ctypes import WinError, wintypes
STDOUT = -11
ERROR_INVALID_HANDLE = 6
kernel32 = ctypes.WinDLL('kernel32', use_errno=True, use_last_error=True)
handle = kernel32.GetStdHandle(STDOUT)
# Assume we set argtypes/restype for all win api functions here
if handle == wintypes.HANDLE(-1).value:
raise WinError()
console_mode = wintypes.DWORD(0)
# We use GetConsoleMode here but it could be any function that expects a
# valid console handle
retval = kernel32.GetConsoleMode(handle, ctypes.byref(console_mode))
# Are the following assertions always true?
if retval == 0:
errno = ctypes.get_last_error()
if errno == ERROR_INVALID_HANDLE:
print('Invalid handle')
assert not sys.stdout.isatty()
else:
# Another error happened
raise WinError()
else:
assert sys.stdout.isatty()
我试图搜索CPython源代码,但找不到任何可以证实或否认这一点的东西。也许有人对代码库更有经验,可以为我指出正确的方向
编辑:我知道CONOUT$+^{sys.stdout
之间的关系
您可以使用CreateFile获取控制台的输出句柄,然后在调用windows控制台API时将该句柄用作参数
参考:Console Handles
在C++中,看起来是这样的,它运行良好,您可以根据需要将其转换为python代码
更新:
retval
返回1。它们都将在test.txt中打印当您删除
sys.stdout = open('test.txt', 'w')
时相关问题 更多 >
编程相关推荐