@@ -908,24 +908,42 @@ python3_loaded(void)
908
908
static wchar_t * py_home_buf = NULL ;
909
909
910
910
#if defined(MSWIN ) && (PY_VERSION_HEX >= 0x030500f0 )
911
- // Python 3.5 or later will abort inside Py_Initialize() when stdin is
912
- // redirected. Reconnect stdin to NUL.
911
+ /*
912
+ * Return TRUE if stdin is readable from Python 3.
913
+ */
914
+ static BOOL
915
+ is_stdin_readable (void )
916
+ {
917
+ DWORD mode , eventnum ;
918
+ struct _stat st ;
919
+ int fd = fileno (stdin );
920
+ HANDLE hstdin = (HANDLE )_get_osfhandle (fd );
921
+
922
+ // Check if stdin is connected to the console.
923
+ if (GetConsoleMode (hstdin , & mode ))
924
+ // Check if it is opened as input.
925
+ return GetNumberOfConsoleInputEvents (hstdin , & eventnum );
926
+
927
+ return _fstat (fd , & st ) == 0 ;
928
+ }
929
+
930
+ // Python 3.5 or later will abort inside Py_Initialize() when stdin has
931
+ // been closed (i.e. executed by "vim -"). Reconnect stdin to CONIN$.
913
932
// Note that the python DLL is linked to its own stdio DLL which can be
914
933
// differ from Vim's stdio.
915
934
static void
916
935
reset_stdin (void )
917
936
{
918
937
FILE * (* py__acrt_iob_func )(unsigned ) = NULL ;
919
938
FILE * (* pyfreopen )(const char * , const char * , FILE * ) = NULL ;
920
- char * stdin_name = "NUL" ;
921
939
HINSTANCE hinst ;
922
940
923
941
# ifdef DYNAMIC_PYTHON3
924
942
hinst = hinstPy3 ;
925
943
# else
926
944
hinst = GetModuleHandle (PYTHON3_DLL );
927
945
# endif
928
- if (hinst == NULL )
946
+ if (hinst == NULL || is_stdin_readable () )
929
947
return ;
930
948
931
949
// Get "freopen" and "stdin" which are used in the python DLL.
@@ -938,14 +956,12 @@ reset_stdin(void)
938
956
if (hpystdiodll )
939
957
pyfreopen = (void * )GetProcAddress (hpystdiodll , "freopen" );
940
958
}
941
- if (isatty (fileno (stdin )))
942
- stdin_name = "CONIN$" ;
943
959
944
- // Reconnect stdin to NUL or CONIN$.
960
+ // Reconnect stdin to CONIN$.
945
961
if (pyfreopen != NULL )
946
- pyfreopen (stdin_name , "r" , py__acrt_iob_func (0 ));
962
+ pyfreopen ("CONIN$" , "r" , py__acrt_iob_func (0 ));
947
963
else
948
- freopen (stdin_name , "r" , stdin );
964
+ freopen ("CONIN$" , "r" , stdin );
949
965
}
950
966
#else
951
967
# define reset_stdin ()
0 commit comments