如何通过sh文件运行python

在日常工作中,我们经常需要通过shell脚本运行Python脚本来完成一些自动化任务。本文将介绍如何通过一个shell脚本来运行Python脚本,并通过示例代码演示如何解决一个实际问题。

问题描述

假设我们有一个Python脚本hello.py,其内容如下:

# hello.py
def say_hello(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    say_hello("Alice")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

我们希望编写一个shell脚本run.sh,通过运行该脚本来执行hello.py脚本,并传递参数,使其输出"Hello, Alice!"。

解决方案

编写shell脚本

首先,我们需要编写一个shell脚本run.sh,用于运行Python脚本并传递参数。内容如下:

#!/bin/bash

python hello.py "$1"
  • 1.
  • 2.
  • 3.

在上面的shell脚本中,使用python hello.py "$1"命令来运行hello.py脚本,并传递第一个参数。

运行Python脚本

接下来,我们需要在终端中运行run.sh脚本,并传递参数。假设我们要传递的参数是Bob,则可以执行以下命令:

bash run.sh Bob
  • 1.

这样,Python脚本将输出"Hello, Bob!"。

示例

现在,我们通过一个示例来演示如何使用上面的方法解决一个实际问题。

假设我们有一个任务,需要在每天早上9点给公司员工发送一封早安邮件。我们可以编写一个Python脚本send_email.py,其内容如下:

# send_email.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, message, to_email):
    email = "your_email_address"
    password = "your_email_password"
    
    msg = MIMEMultipart()
    msg['From'] = email
    msg['To'] = to_email
    msg['Subject'] = subject
    
    msg.attach(MIMEText(message, 'plain'))
    
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email, password)
    text = msg.as_string()
    server.sendmail(email, to_email, text)
    server.quit()

if __name__ == "__main__":
    subject = "Good Morning!"
    message = "Hello, everyone! Have a great day!"
    to_email = "recipient@example.com"
    
    send_email(subject, message, to_email)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

然后,我们编写一个shell脚本send_email.sh,内容如下:

#!/bin/bash

python send_email.py
  • 1.
  • 2.
  • 3.

最后,在终端中运行以下命令:

bash send_email.sh
  • 1.

这样,每天早上9点,公司员工将收到一封早安邮件。

状态图

Running Completed Failed

序列图

PythonScript ShellScript User PythonScript ShellScript User 运行 send_email.sh 运行 send_email.py 发送邮件 完成 完成任务

结论

通过编写一个shell脚本来运行Python脚本,可以方便地实现自动化任务。在实际工作中,我们可以根据需要编写不同的Python脚本,并通过shell脚本来执行它们,从而提高工作效率。希望本文能帮助读者更好地理解如何通过sh文件运行Python。