2017-07-31 23 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腳本輸出格式 –

相關問題