python - 如何使用 cron 作业运行 python 文件

标签 python shell cron

您好,我创建了一个 python 文件,例如 file_example.py

文件会输出sensex值

假设文件在linux系统上的路径是/Desktop/downloads/file_example.py

我通常会像 python file_example.py

这样运行文件

但我想设置一个 cron 作业以每 2 分钟运行一次位于上述路径的 python 文件

谁能告诉我怎么做

编辑代码:

我已经编辑了代码并创建了一个名为 test.sh 的 bash 脚本,如下所示

#!/bin/bash 
cd /Desktop/downloads/file_example.py
python file_example.py 2>log.txt 

当我运行上述文件时,显示如下错误:

sh-4.2$ python test.sh
  File "test.sh", line 3
    python test.py 2>log.txt 
              ^
SyntaxError: invalid syntax

最佳答案

假设您使用的是 unix 操作系统,您将执行以下操作。

使用命令编辑 crontab 文件

crontab -e

添加一行类似于下面的行

*/2 * * * * /Desktop/downloads/file_example.py

这可用于运行其他脚本,只需使用所需脚本的路径即可,即

*/2 * * * * /path/to/script/to/run.sh

时间说明如下(在数字前添加星号和斜线以每 n 个时间步运行一次,在本例中为每 2 分钟一次)

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

关于python - 如何使用 cron 作业运行 python 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774925/

相关文章:

java - 如何在 AppEngine 中注销 CRON 作业?

python - Apache2&Django - NameError : name "AttributeError" is not defined

python - 如何强制关闭顶级窗口的消息框

python - 双变音位算法的最佳/最差/平均时间效率是多少?

python - 需要关于如何在 python 中下载文件的明确解释

linux - 如何在不同的 shellscsh/tcsh shell 上执行 sh shell 脚本?

c - 在我的 shell 中实现管道

bash - 如何获取 `ls` 命令的前 n 行

docker - 在 Alpine 容器中启用 crond

cron - cron、crontab 和 cronjob 之间的区别?