I am using a python script to create a shell script that I would ideally like to annotate with comments. If I want to add strings with hashtags in them to a code section like this:
with open(os.path.join("location","filename"),"w") as f:
file = f.read()
file = """my_function() {{
if [ $# -eq 0 ]
then
echo "Please supply an argument"
return
fi
echo "argument is $1"
}}
"""
with open(os.path.join("location","filename"),"w") as f:
f.write(file)
what is the best way I can accomplish this?
CodePudding user response:
You already have a #
character in that string literal, in $#
, so I'm not sure what the problem is.
Python considers a """
string literal as one big string, newlines, comment-esque sequences and all, as you've noticed, until the ending """
.
To also pass escape characters (e.g. \n
as \n
, not a newline) through raw, you'd use r"""..."""
.
In other words, with
with open("x", "w") as f:
f.write("""x
hi # hello world
""")
you end up with a file containing
x
hi # hello world
CodePudding user response:
In terms of your wider goal, to write a file with a bash function file from a Python script seems a little wayward.
This is not really a reliable practise, if your use case specifically requires you to define a bash function via script, please explain your use case further. A cleaner way to do this would be:
Define an .sh file and read contents in from there:
# function.sh
my_function() {{
# Some code
}}
Then in your script:
with open('function.sh', 'r') as function_fd:
# Opened in 'append' mode so that content is automatically appended
with open(os.path.join("location","filename"), "a") as target_file:
target_file.write(function_fd.read())