I am trying to write a script file via a Python script
For that I have defined a function to open, write & close file
def funcToCreateScript(filename,filecontent)
I have another function, where I am calling funcToCreateScript and am trying to pass it shell script content through a variable. The problem is when I format the text as below
def createfile():
var = """#!/bin/sh
echo ${test}
"""
funcToCreateScript(filename,var)
I get the output of script as –
#!/bin/sh
echo ${test}
So, its taking the function’s indentation and writing it accordingly. Is there a way to format it so that it will look like
#!/bin/sh
echo ${test}
e.g. –
def main():
var = """
#!/bin/sh
echo ${test}
"""
print var
main()
> test.py
#!/bin/sh
echo ${test}
There are two solutions here, either use the new line escape character (‘\n’), so it would look like:
Keep in mind, if you use this technique (which is pretty nasty solution – see below for a better alternative), and you want to see the output you’ll need to
print()(assuming Python 3.0 standards here).Or, just simply do:
I am not sure how you got
funcToCreateScriptsetup, but here is some trial code so you can see it in action (copy and paste into an interactive interpreter or new python file and run):If you want to get fancy, but still make it readable you can use lstrip(” “) which will remove all white space from the left side.
Just be weary of the last solution because if you have whitespace that you intended to have there, then it’ll strip that away (I personally like option 2 I listed).