2017-07-31 62 views
0

我有一个需要写一个小bash脚本到/tmp目录,将提示输入凭据的程序:当我现在看起来它写写一个新的行字符,而无需创建一个新的行

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

像这样当cat'编:

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) 
+0

只是转义反斜杠像'\\ n' –

回答

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

你可以把你的多行文字三重引号内:

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

所以你不必在每一行的结尾处关注\n

+1

给予'printf'的字符串中的'\ n'应该仍然存在,因为它看起来是所需的bash脚本输出格式 –

相关问题