@@ -327,11 +327,17 @@ impl VirtualMachine {
327327 let line_buffering = buffered_stdio && ( isatty || fd == 2 ) ;
328328
329329 let newline = if cfg ! ( windows) { None } else { Some ( "\n " ) } ;
330+ // stderr uses backslashreplace error handler
331+ let errors: Option < & str > = if fd == 2 {
332+ Some ( "backslashreplace" )
333+ } else {
334+ None
335+ } ;
330336
331337 let stdio = self . call_method (
332338 & io,
333339 "TextIOWrapper" ,
334- ( buf, ( ) , ( ) , newline, line_buffering, write_through) ,
340+ ( buf, ( ) , errors , newline, line_buffering, write_through) ,
335341 ) ?;
336342 let mode = if write { "w" } else { "r" } ;
337343 stdio. set_attr ( "mode" , self . ctx . new_str ( mode) , self ) ?;
@@ -853,7 +859,13 @@ impl VirtualMachine {
853859 [ arg] => match_class ! ( match arg {
854860 ref i @ PyInt => {
855861 use num_traits:: cast:: ToPrimitive ;
856- return i. as_bigint( ) . to_u32( ) . unwrap_or( 0 ) ;
862+ // Try u32 first, then i32 (for negative values), else -1 for overflow
863+ let code = i
864+ . as_bigint( )
865+ . to_u32( )
866+ . or_else( || i. as_bigint( ) . to_i32( ) . map( |v| v as u32 ) )
867+ . unwrap_or( -1i32 as u32 ) ;
868+ return code;
857869 }
858870 arg => {
859871 if self . is_none( arg) {
@@ -866,8 +878,11 @@ impl VirtualMachine {
866878 _ => args. as_object ( ) . repr ( self ) . ok ( ) ,
867879 } ;
868880 if let Some ( msg) = msg {
869- let stderr = stdlib:: sys:: PyStderr ( self ) ;
870- writeln ! ( stderr, "{msg}" ) ;
881+ // Write using Python's write() to use stderr's error handler (backslashreplace)
882+ if let Ok ( stderr) = stdlib:: sys:: get_stderr ( self ) {
883+ let _ = self . call_method ( & stderr, "write" , ( msg, ) ) ;
884+ let _ = self . call_method ( & stderr, "write" , ( "\n " , ) ) ;
885+ }
871886 }
872887 1
873888 } else if exc. fast_isinstance ( self . ctx . exceptions . keyboard_interrupt ) {
0 commit comments