简体   繁体   中英

store formatted text in variable python

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}

eg -

def main():
    var = """
        #!/bin/sh
        echo ${test}
        """
    print var

main()

 > test.py

                #!/bin/sh
                echo ${test}

One way is to use textwrap.dedent :

textwrap.dedent( text )

Remove any common leading whitespace from every line in text.

This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.

import textwrap

def createfile():
    var = """\
          #!/bin/sh
          echo ${test}
          """
    var = textwrap.dedent(var)
    funcToCreateScript(filename, var)

Note that \\ is inserted immediately after the opening triple-quotes in order to avoid an empty line.

There are two solutions here, either use the new line escape character ('\\n'), so it would look like:

def createfile():
    var = """#!/bin/sh\necho ${test}"""
    funcToCreateScript(filename,var)

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:

def createfile():
    involved. 
    var = """#!/bin/sh
echo ${test}
          """
    return funcToCreateScript(filename,var)

I am not sure how you got funcToCreateScript setup, 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):

def createfile():
    var = """
#!/bin/sh
echo ${test}
          """
    return var

v = createfile()

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.

def createfile():
    var = """#!/bin/sh
             echo ${test}
          """
    script_txt = ""

    for line in var:
        script_txt += line.lstrip(" ")

    return script_txt

v = createfile()

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).

If the last line of the variable consists only of spaces, and if its length is the number of spaces that should be removed from the beginning of lines of var other than the first, consider code like the following:

v = var.split('\n')
s = len(v[-1])
var = v[0]+'\n'+'\n'.join(map(lambda x: x[s:], v[1:]))

This strips s extra characters off the fronts of lines other than the first. If some alignment is done using tabs, the above could cause problems; one might want to use string replacement rather than array slicing.

尝试这个:

var = """#!/bin/sh\necho ${test}"""

Another option - implicit concatenation:

def createfile():
    var = (
        "#!/bin/sh\n"
        "echo ${test}"
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM