【问题标题】:Write a new line character without creating a new line写入换行符而不创建新行
【发布时间】:2017-07-31 13:15:54
【问题描述】:

我有一个程序需要向/tmp 目录写入一个小 bash 脚本,以提示输入凭据:

linux_prompt_script = (
    'printf "Proxy authentication failed.\n"'
    '\nread -s -p "Enter Password to try again: " mypassword'
    '\nprintf "Proxy authentication succeeded\n'
)

当我现在写它时,cat'ed 时看起来像这样:

printf "Proxy authentication failed.
"
read -s -p "Enter Password to try again: " mypassword
printf "Proxy authentication succeeded

这显然行不通。有没有办法可以在不创建新行的情况下写一个换行符\n,也可以写它来创建一个新行?

到目前为止我所拥有的:

linux_prompt_script = (
    'printf "Proxy authentication failed.\n"'
    '\nread -s -p "Enter Password to try again: " mypassword'
    '\nprintf "Proxy authentication succeeded\n'
)


def _prompt_linux():

    def _rand_filename(chars=string.ascii_letters):
        retval = set()
        for _ in range(0, 6):
            retval.add(random.choice(chars))
        return ''.join(list(retval))

    filename = _rand_filename()
    filepath = "/tmp/{}.sh".format(filename)
    while True:
        with open(filepath, "a+") as sh:
            sh.write(linux_prompt_script)

【问题讨论】:

  • 只需像\\n一样转义反斜杠

标签: python python-2.7 newline


【解决方案1】:

原始字符串在这里很有用。引号前的r 前缀表示一个原始字符串,它可以防止处理转义字符:

linux_prompt_script = r'''
printf "Proxy authentication failed.\n"
read -s -p "Enter Password to try again: " mypassword
printf "Proxy authentication succeeded"
'''

with open(filepath, "a+") as sh:
    sh.write(linux_prompt_script)

【讨论】:

    【解决方案2】:

    您可以将多行文本放在三引号内:

    text='''
    printf "Proxy authentication failed.
    read -s -p "Enter Password to try again: " mypassword
    printf "Proxy authentication succeeded
    '''
    

    所以你不必介意每一行末尾的\n

    【讨论】:

    • printf 的字符串中的\n 应该仍然存在,因为它似乎是 bash 脚本输出的所需格式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2013-02-10
    • 2019-11-18
    相关资源
    最近更新 更多