Shell-Script
如何在 bash 腳本中包含 python 腳本
我需要在 bash 腳本中包含以下 python 腳本。
如果 bash 腳本結束成功,我需要執行以下腳本:
#!/usr/bin/python from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('192.168.75.1', 25) smtp.login('my_mail', 'mail_passwd') from_addr = "My Name <my_mail@192.168.75.1>" to_addr = "<my_mail@192.168.75.1" subj = "Process completed" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) #print (date) message_text = "Hai..\n\nThe process completed." msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
如果要將 bash 和 python 腳本的原始碼放在一起,可以使用 heredoc。例如,假設以下是名為 的文件的內容
pyinbash.sh
:#!/bin/bash echo "Executing a bash statement" export bashvar=100 cat << EOF > pyscript.py #!/usr/bin/python import subprocess print 'Hello python' subprocess.call(["echo","$bashvar"]) EOF chmod 755 pyscript.py ./pyscript.py
現在執行
pyinbash.sh
將產生:$ chmod 755 pyinbash.sh $ ./pyinbash.sh Exe
只需將 HereDoc 傳遞給
python -
.從 python 幫助
python -h
:
- : program read from stdin
#!/bin/bash MYSTRING="Do something in bash" echo $MYSTRING python - << EOF myPyString = "Do something on python" print myPyString EOF echo "Back to bash"