简体   繁体   English

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

[英]How to run a python file using cron jobs

Hi I have created a python file for example as file_example.py嗨,我创建了一个 python 文件,例如file_example.py

The file will output the sensex value该文件将输出 sensex 值

Suppose the path of the file on linux system is /Desktop/downloads/file_example.py假设linux系统上文件的路径是/Desktop/downloads/file_example.py

and I normally will run the file like python file_example.py我通常会像python file_example.py一样运行文件

But I want to set a cron job to run the python file every 2 min which is located at the above path但是我想设置一个 cron 作业来每 2 分钟运行一次位于上述路径的 python 文件

Can anyone please let me know how to do this任何人都可以让我知道如何做到这一点

Edited Code :编辑代码

I had edited the code and created a bash script with the name test.sh as indicated below我编辑了代码并创建了一个名为 test.sh 的 bash 脚本,如下所示

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

When I run the above file, the following error is displayed:当我运行上述文件时,显示以下错误:

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

Assuming you are using a unix OS, you would do the following.假设您使用的是 unix 操作系统,您将执行以下操作。

edit the crontab file using the command使用命令编辑 crontab 文件

crontab -e

add a line that resembles the one below添加类似于下面的一行

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

this can be used to run other scripts simply use the path to the script needed ie这可用于运行其他脚本,只需使用所需脚本的路径即可

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

An explanation of the timing is below (add a star and slash before number to run every n timesteps, in this case every 2 minutes)时间的解释如下(在数字前添加一个星号和斜线以每 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)

You can use python-crontab module.您可以使用 python-crontab 模块。

https://pypi.python.org/pypi/python-crontab https://pypi.python.org/pypi/python-crontab

To create a new cron job is as simple as follows:创建一个新的 cron 作业非常简单,如下所示:

from crontab import CronTab
#init cron
cron   = CronTab()

#add new cron job
job  = cron.new(command='/usr/bin/echo')

#job settings
job.hour.every(4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM