Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a new text file using heredoc

Tags:

python

heredoc

In my shell script, I use heredoc block to create a file on the fly. What is the python equivalent?

cat > myserver.pem << "heredoc"
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAnTsiYssvsuM1DRjyhqD8+ZB8ESqUFHgzeBYONp3yqjK8ICw/LRrxjXGXidAW
aPBXfktv3zN/kFsLMEFJKrJs/TLCfXG1CwFHMZzJRLM4aE6E0j6j+KF96cY5rfAo82rvP5kQdTIm
-----END RSA PRIVATE KEY-----
heredoc

I am looking for a simple solution. I really like the above shell script code. Can I use it "as is" in python?

like image 741
shantanuo Avatar asked Dec 17 '13 06:12

shantanuo


1 Answers

You can't use the code as-is, but you can simply use a triple-quoted string for the text, and combine it with the usual file manipulation built-ins:

with open("myserver.pem", "w") as w:
    w.write("""\
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAnTsiYssvsuM1DRjyhqD8+ZB8ESqUFHgzeBYONp3yqjK8ICw/LRrxjXGXidAW
aPBXfktv3zN/kFsLMEFJKrJs/TLCfXG1CwFHMZzJRLM4aE6E0j6j+KF96cY5rfAo82rvP5kQdTIm
-----END RSA PRIVATE KEY-----
""")

If you wanted to simulate the shell's >> operator, you'd pass "a" as the mode to open.

like image 74
user4815162342 Avatar answered Sep 17 '22 17:09

user4815162342