Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape any of the special shell characters in a Python string?

Tags:

python

bash

shell

How can I escape any of the special shell characters in a Python string?

The following characters need to be escaped:

$,!,#,&,",',(,),|,<,>,`,\,;

For example say I have this string:

str="The$!cat#&ran\"'up()a|<>tree`\;"

TIA

like image 583
Sam Roberts Avatar asked Jan 24 '15 00:01

Sam Roberts


People also ask

How do you escape special characters in a string in Python?

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.

How do you escape special characters in Shell?

Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.

How do you escape a Python shell?

Escape slashes and double-quotes. Surround entire command with double quotes so the command argument cannot be maliciously broken and commandeered with spaces.

How do you escape characters in a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .


2 Answers

In Python3, the required batteries are included as shlex.quote.

shlex.quote(s)

Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line […].

In your example:

import shlex

s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))

Output:

'The$!cat#&ran"'"'"'up()a|<>tree`\;'
like image 124
5gon12eder Avatar answered Oct 20 '22 03:10

5gon12eder


re.sub will do the job:

re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)

Output

The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;
like image 37
buydadip Avatar answered Oct 20 '22 05:10

buydadip