我正在嘗試發送多行文本:
text = "This is a line 1
This is a line 2
This is a line 3"
在 python 腳本中:
cmd = "echo {} | mail -s 'Test email' [email protected]".format(text)
os.system(cmd)
但我收到一個錯誤,因為新行被解釋為命令:
sh: line 1: This: command not found
列印出來,結果是:
echo This is line 1
This is line 2
This is line 3 | mail -s 'Test email' [email protected]
我認為解決方案很簡單,但我沒有找到任何有用的解決方案。
uj5u.com熱心網友回復:
直接的問題是,如果 shell 中的字串包含換行符等,則需要參考它們。請參閱何時在 shell 變數周圍加上引號。
但更根本的是,你真的不想在os.system這里這樣使用。就像它的檔案已經告訴你的那樣,你通常更喜歡subprocess.
import subprocess
subprocess.run(
["mail", "-s", "Test email", "[email protected]"],
input=text, text=True, check=True)
或使用smtplib本機發送電子郵件(或者相反,如果您只需要一個簡單的 shell 腳本,則根本不要使用 Python,盡管您仍然需要修復參考)。
mail便攜性很差,所以如果你還沒有在你的系統上測驗過這個,它可能會有額外的問題。也許另請參閱如何使用 Linux 命令列將檔案作為電子郵件附件發送?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472949.html
