我试图通过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}
这里有两种解决方案,要么使用新行转义符('\n'),因此它看起来像:
请记住,如果您使用这种技术(这是一个非常糟糕的解决方案—请参阅下面的更好的替代方案),并且希望看到您需要的输出
print()
(这里假设使用Python3.0标准)。在或者,只需:
^{pr2}$我不知道您是如何得到
funcToCreateScript
设置的,但这里有一些试用代码,以便您可以看到它的实际操作(复制并粘贴到交互式解释器或新的python文件并运行):如果你想变得花哨,但仍然让它可读,你可以使用lstrip(“”),它将删除左侧的所有空白。在
只是厌倦了最后一个解决方案,因为如果你有你想要的空白,那么它会把它去掉(我个人喜欢我列出的选项2)。在
如果变量的最后一行只由空格组成,并且它的长度是从
var
的行首(而不是第一行)开始删除的空格数,请考虑如下代码:这会将
s
个额外字符从第一行以外的行的前面去掉。如果使用制表符进行某些对齐,则上述操作可能会导致问题;可能需要使用字符串替换而不是数组切片。在一种方法是使用textwrap.dedent:
请注意,
\
紧跟在左三引号后面,以避免出现空行。在相关问题 更多 >
编程相关推荐