cybertextron cybertextron - 16 days ago 4
Python Question

Format a string in python

I have the following template, which I'm writing to a

config
file:

template = """mkdir /root/.ssh \
&& chmod go-rwx /root/.ssh \
&& apt-get install -y \
gcc \
libssl-dev \
python-pip \
openssh-server \
PATH=/usr/local/jdk1.8.0/bin:$PATH
"""
with open('config', 'w') as f:
f.write(template)


I'm getting the following format:

mkdir /root/.ssh && chmod go-rwx /root/.ssh && apt-get install -y gcc libssl- dev python-pip openssh-server


instead of:

mkdir /root/.ssh \
&& chmod go-rwx /root/.ssh \
&& apt-get install -y \
gcc \
libssl-dev \
python-pip \
openssh-server \
PATH=/usr/local/jdk1.8.0/bin:$PATH


How can I format my string template to the correct format?

Answer

In Python \ is an escape character, you have to escape it with \\:

template = """mkdir /root/.ssh \\
        && chmod go-rwx /root/.ssh \\
        && apt-get install -y \\
            gcc \\
            libssl-dev \\
            python-pip \\
            openssh-server \\
PATH=/usr/local/jdk1.8.0/bin:$PATH 
"""
with open('config', 'w') as f:
    f.write(template)