Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

How to prevent automatic escaping of special characters in Python

I'm writing a Python script that accepts file paths as strings, parses them, appends a command name, and builds a list, which is then passed to subprocess.Popen() for execution. This script is to handle both Unix and Windows file paths, and ultimately should run on both systems.

When I run this under Unix, if I give a Windows path that inadvertently contains an escape character (e.g. UsersAdministratorin), Python will interpret the embedded as the backspace character. I want to prevent that from happening.

As far as I know, there's no function or method to denote a string variable as a raw string. The 'r' modifier only works for string constants.

So far, the closest I've been able to get is this:

winpath = "C:UsersAdministratorin" 
winpath = winpath.replace('','\b')
winpathlist = winpath.split('\') 

At this point, winpathlist should contain ['C:','Users','Administrator','bin'], not ['C','Users','Administratorx08in'].

I can add additional calls to winpath.replace() to handle the other escapes I might get -- a, f, , , , v -- but not x.

Is there a more pythonic way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your winpath is hard-coded, you may want to use r before your string to indicate it is a "raw string".

winpath = r"C:UsersAdministratorin"

If winpath cannot be hardcoded, you can try to create a new string as:

escaped_winpath = "%r" % winpath

(which is just repr(winpath), and won't really help you, as repr("in") is...)

A solution would be to rebuild the string from scratch: you can find an example of function at that link, but the generic idea is:

escape_dict={'a':r'a',
             '':r'',
             'c':r'c',
             'f':r'f',
             '
':r'
',
             '
':r'
',
             '':r'',
             'v':r'v',
             ''':r''',
             '"':r'"'}

def raw(text):
    """Returns a raw string representation of text"""
    new_string=''
    for char in text:
        try: 
            new_string += escape_dict[char]
        except KeyError: 
            new_string += char
    return new_string

and now, raw("in") gives you "\bin" (and not "\x08in")...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...