文章目录
python 定时执行shell 命令
要在Python中设置定时任务执行shell命令,你可以使用subprocess
模块来执行命令,以及time
模块来处理计时。以下是一个简单的例子,演示如何定期执行不同间隔的shell命令:
import subprocess
import time
def run_shell_command(command):
try:
# 执行shell命令
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
# 每隔一定时间执行命令的函数
def schedule_command(command, interval):
while True:
run_shell_command(command)
time.sleep(interval)
# 每过20小时执行一次的命令
def every_20_hours_command(command):
schedule_command(command, 20 * 3600)
# 每过一分钟执行一次的命令
def every_minute_command(command):
schedule_command(command, 60)
# 每过一秒钟执行一次的命令
def every_second_command(command):
schedule_command(command, 1)
# 示例命令
shell_command = "echo 'Hello, World!'"
# 根据需要选择函数并取消注释
# every_20_hours_command(shell_command)
# every_minute_command(shell_command)
# every_second_command(shell_command)
在上述代码中:
run_shell_command
函数使用subprocess.run
执行给定的shell命令。如果执行时发生错误,异常会被捕获,并打印出来。schedule_command
函数是一个无限循环,用于执行给定的shell命令,并在执行后暂停指定的时间间隔(以秒为单位)。every_20_hours_command
、every_minute_command
和every_second_command
函数分别设置了不同的时间间隔,并调用了schedule_command
函数。
在这个脚本中,shell_command
是你想要定期执行的shell命令。你可以将其换成任何有效的shell命令。