9

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?

Monika
  • 2,172
  • 15
  • 24
shantanuo
  • 31,689
  • 78
  • 245
  • 403

1 Answers1

15

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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355