在不创建新行的情况下编写新行字符

时间:2017-07-31 13:15:55

标签: python python-2.7 newline

我有一个程序需要在/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)

2 个答案:

答案 0 :(得分:0)

原始字符串在这里很有用。引号前面的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)

答案 1 :(得分:0)

您可以将多行文字放在三重引号中:

\n

因此,您不必在每一行的末尾都考虑$(document).ready(function() { $('#second').on('change keyup paste', function(event) { event.preventDefault(); $(this).val($('#first').val()); }); });