Mihai Vilcu
Mihai Vilcu

Reputation: 1967

python subprocess newlines are escaped

I'm running an mysql query in the command line using subprocess.Popen

process = subprocess.Popen(conarray, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

r = process.stdout.readlines()

stdout = [x.decode('utf8').rstrip() for x in r]

later I write the output in a file

f = open(file_name, 'w+', encoding='utf8')
f.write(templates[idx])

It works fine but for some reason all newlines(\n) and tabs(\t) are escaped.

\t<div id="container">\n\t\t<a name="top"

Any idea on how I can fix that ?

Upvotes: 1

Views: 3787

Answers (2)

Mihai Vilcu
Mihai Vilcu

Reputation: 1967

It turns out that in order to make them work I also needed to apply unicode-escape on that string.
But unicode-escape does NOT work in general.

>>> s = 'naïve \\t test'
>>> print(s.encode('utf-8').decode('unicode_escape'))
naïve   test

The best solution I could find is described in this answer

Upvotes: 1

falsetru
falsetru

Reputation: 369124

If you print the whole sequence object, repr(list_object) is printed. That's the way Python represent it.

>>> lst = ['\t<div id="container">\n\t\t<a name="top"']
>>> print(lst)
['\t<div id="container">\n\t\t<a name="top"']
>>> print(lst[0])
        <div id="container">
                <a name="top"
>>>

Upvotes: 1

Related Questions