-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect OSError raised when redirecting to NUL on Windows #1065
Comments
I added an additional check based on MSDN’s suggestion: --- a/click/_winconsole.py
+++ b/click/_winconsole.py
@@ -33,6 +33,8 @@ kernel32 = windll.kernel32
GetStdHandle = kernel32.GetStdHandle
ReadConsoleW = kernel32.ReadConsoleW
WriteConsoleW = kernel32.WriteConsoleW
+WriteFile = kernel32.WriteFile
+GetConsoleMode = kernel32.GetConsoleMode
GetLastError = kernel32.GetLastError
GetCommandLineW = WINFUNCTYPE(LPWSTR)(
('GetCommandLineW', windll.kernel32))
@@ -156,7 +158,11 @@ class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
MAX_BYTES_WRITTEN) // 2
code_units_written = c_ulong()
- WriteConsoleW(self.handle, buf, code_units_to_be_written,
+ if GetConsoleMode(self.handle, byref(c_ulong())):
+ WriteConsoleW(self.handle, buf, code_units_to_be_written,
+ byref(code_units_written), None)
+ else:
+ WriteFile(self.handle, buf, code_units_to_be_written,
byref(code_units_written), None)
bytes_written = 2 * code_units_written.value This checks if the handle is actually a console with I am not very familiar with Windows API, and would like some input whether this is actually a good idea. |
We shouldn't even be using this code if stdio is redirected, but Windows, being Windows, catches us off guard here: https://bugs.python.org/issue28654. In essence, CPython itself uses P.S. @davidism Why is this code used on CPython 3.6+ where the Windows Unicode console hack is implemented by CPython itself? |
isatty returns True for the NUL device on Windows. So use GetConsoleMode instead to detect a console handle. See https://bugs.python.org/issue28654 Fixes pallets#1065
isatty returns True for the NUL device on Windows. So use GetConsoleMode instead to detect a console handle. See https://bugs.python.org/issue28654 Fixes pallets#1065
isatty returns True for the NUL device on Windows. So use GetConsoleMode instead to detect a console handle. See https://bugs.python.org/issue28654 Fixes pallets#1065
Reproducible for both Python 3.6 and 3.7. I did not test against older versions.
Tested on the Click 6.x series. Windows 10, Build 17134.
Steps to reproduce:
I believe the problem is that Click tries to be helpful, and raises an error when there are not bytes written when there should be. This is, however, exactly what is expected to happen when you redirect things to
NUL
on Windows.Curiously, however, Windows seems to act a little differently for stderr.
2>NUL
works as expected.The text was updated successfully, but these errors were encountered: