Page 2 of 2 FirstFirst 12
Results 11 to 12 of 12

Thread: [SOLVED] Automatic backslash escape sequences?

  1. #11
    Join Date
    Dec 2006
    Beans
    160
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: Automatic backslash escape sequences?

    Brilliant! That -- trick is just what I need.

  2. #12
    Join Date
    Dec 2006
    Beans
    160
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    bash single quotes

    I just discovered that bash uses single quotes to preserve the literal value of a string (including spaces and stuff). The only problem with that is when your filename includes single quotes, but I found the workaround.

    So here's some code with their results:
    PHP Code:
    import subprocess
    # we need to pass shell as True to let bash interpret the single quotes as it normally would
    subprocess.call("touch 'a new day.txt'"shell=True# creates: a new day.txt
    subprocess.call(r"touch 'a'\''new'\''day.txt'"shell=True# creates: a'new'day.txt 
    Here's a function I wrote to automatically surrond with single quotes, replacing any single quotes with the appropriate string:
    PHP Code:
    #!/usr/bin/env python
    import subprocess

    def surround_with_single_quotes
    (string):
        
    """Surrounds the passed string with single quotes and replaces any
        quotes with '\'' required by bash
        >>> surround_with_single_quotes("
    a'new'day.txt")
        "'a'
    \\\\''new'\\\\''day.txt'"
        
        The previous example returns (without python's quotes and escape sequences):
        'a'\''new'\''day.txt'
        """
        
    str string.replace("'"r"'\''")
        
    str "'" str "'"
        
    return str

    if __name__ == "__main__":
        
    import doctest
        doctest
    .testmod()
        
    subprocess.call("touch " surround_with_single_quotes("a'new'day.txt"), shell=True

Page 2 of 2 FirstFirst 12

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •