General string quoting for TCL

前端 未结 3 687
暗喜
暗喜 2021-02-05 09:25

I\'m writing a utility (which happens to be in python) which is generating output in the form of a TCL script. Given some arbitrary string variable (not unicode) in the python,

3条回答
  •  清酒与你
    2021-02-05 09:48

    To do it right you should also specify the encoding your python string is in, typically sys.getdefaultencoding(). Otherwise you might garble encodings when translating it to Tcl.

    If you have binary data in your string and want Tcl binary strings as a result this will always work:

    data = "".join("\\u00%02x" % ord(c) for c in mystring)
    tcltxt = "set x %s" % data
    

    Will look like a hex dump though, but well, it is a hex dump...

    If you use any special encoding like UTF-8 you can enhance that a bit by using encoding convertfrom/convertto and the appropriate Python idiom.

    data = "".join("\\u00%02x" % ord(c) for c in myutf8string)
    tcltext = "set x [encoding convertfrom utf-8 %s]" % data
    

    You can of course refine this a bit, avoiding the \u encoding of all the non special chars, but the above is safe in any case.

提交回复
热议问题