This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: code.InteractiveConsole interprets escape chars incorrectly
Type: Stage:
Components: Library (Lib) Versions: Python 2.2
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: mwh Nosy List: johahn, markrichardson, mwh
Priority: normal Keywords:

Created on 2003-10-17 18:50 by markrichardson, last changed 2022-04-10 16:11 by admin. This issue is now closed.

Messages (4)
msg18683 - (view) Author: Mark Richardson (markrichardson) Date: 2003-10-17 18:50
code.InteractiveConsole interprets escape characters 
incorrectly. For example, it interprets "\\t" the same 
as "\t", so it prints a tab instead of a backslash t.

to reproduce:

import sys
import code

class MyConsole(code.InteractiveConsole):
    def __init__(self):
        code.InteractiveConsole.__init__(self)

    # I tried it with runsource too. Same result.
    def run_code(self, cmdString):
        self.runcode(cmdString)

    def write(self, data):
        sys.__stdout__.write(data)

instance = MyConsole()
instance.run_code('print "\\thello\\tworld"')
print "\\thello\\tworld"

msg18684 - (view) Author: Johan M. Hahn (johahn) Date: 2003-10-18 09:59
Logged In: YES 
user_id=887415

   You should use the r prefix when passing strings to 
InteractiveConsole to prevent the string from beeing parsed 
twice. This works fine:




>>> instance.run_code(r'print "\\thello\\tworld"')




   The strange behaviour you are experiencing lies with the 
exec statement... it boiles down to:




>>> exec 'print"\\thello\\tworld"'


	hello	world


>>> print "\\thello\\tworld"


\thello\tworld




   The cause is that the inner string in the first call is parsed 
twice... first double backslash '\\' is reduced to '\' prior to the 
exec statement is executed... then before print is called the 
string is parsed again and '\t' becomes a tab. I wouldn't 
classify this as a bug, rather a gotcha. Think of what this line 
means:




>>> exec 'print "hello\nworld"'




...johahn
msg18685 - (view) Author: Michael Hudson (mwh) (Python committer) Date: 2003-10-20 11:31
Logged In: YES 
user_id=6656

as johahn explains, you've been confused by multiple levels
of escaping.  closing.
msg18686 - (view) Author: Mark Richardson (markrichardson) Date: 2003-10-20 15:31
Logged In: YES 
user_id=889309

Thanks for the clarification on this one.
History
Date User Action Args
2022-04-10 16:11:47adminsetgithub: 39425
2003-10-17 18:50:52markrichardsoncreate