Executing Python Scripts via Shell Scripts
Running Python Scripts from Shell Files
Shell scripts provide a convenient way to execute Python programs, particularly for automtaion tasks. This approach allows for parameter passing and shceduled execution.
Basic Implementation
Consider a Python script greet.py that outputs a personalized message:
# greet.py
def display_greeting(recipient):
print(f"Good day, {recipient}!")
if __name__ == "__main__":
display_greeting("Charlie")
To execute this via a shell script execute.sh:
#!/bin/bash
python greet.py "$1"
Run the script with:
bash execute.sh David
This will output: "Good day, David!"
Practical Example: Auotmated Notifications
For a daily notification system, create notify.py:
# notify.py
import smtplib
from email.message import EmailMessage
def send_notification(subject, content, recipient):
sender = "notifications@example.com"
password = "secure_password"
msg = EmailMessage()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
msg.set_content(content)
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(sender, password)
server.send_message(msg)
if __name__ == "__main__":
send_notification("Daily Update", "Here's your morning briefing", "team@company.com")
Create a corresponding shell script daily_notify.sh:
#!/bin/bash
python notify.py
Schedule execution with cron:
0 9 * * * /path/to/daily_notify.sh
This setup will send daily emails at 9 AM.