在变量python中存储格式化文本

2024-10-04 07:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过Python脚本编写一个脚本文件

为此,我定义了一个打开、写入和关闭文件的函数 def funcToCreateScript(filename,filecontent)

我还有另一个函数,我调用funcToCreateScript,并试图通过一个变量将shell脚本内容传递给它。问题是当我将文本格式化如下

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

我得到脚本的输出为-

^{pr2}$

因此,它获取函数的缩进并相应地编写它。有没有一种方法可以格式化它,使它看起来像

#!/bin/sh
echo ${test}

例如-

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

main()

 > test.py

                #!/bin/sh
                echo ${test}

Tags: 文件函数testecho脚本bin定义main
3条回答

这里有两种解决方案,要么使用新行转义符('\n'),因此它看起来像:

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

请记住,如果您使用这种技术(这是一个非常糟糕的解决方案—请参阅下面的更好的替代方案),并且希望看到您需要的输出print()(这里假设使用Python3.0标准)。在

或者,只需:

^{pr2}$

我不知道您是如何得到funcToCreateScript设置的,但这里有一些试用代码,以便您可以看到它的实际操作(复制并粘贴到交互式解释器或新的python文件并运行):

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

v = createfile()

如果你想变得花哨,但仍然让它可读,你可以使用lstrip(“”),它将删除左侧的所有空白。在

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

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

    return script_txt

v = createfile()

只是厌倦了最后一个解决方案,因为如果你有你想要的空白,那么它会把它去掉(我个人喜欢我列出的选项2)。在

如果变量的最后一行只由空格组成,并且它的长度是从var的行首(而不是第一行)开始删除的空格数,请考虑如下代码:

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

这会将s个额外字符从第一行以外的行的前面去掉。如果使用制表符进行某些对齐,则上述操作可能会导致问题;可能需要使用字符串替换而不是数组切片。在

一种方法是使用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)

请注意,\紧跟在左三引号后面,以避免出现空行。在

相关问题 更多 >