如何使用cron作业运行python文件 [英] How to run a python file using cron jobs
问题描述
您已经创建了一个python文件,例如 file_example.py
Hi I have created a python file for example as file_example.py
文件将输出sensex
The file will output the sensex value
假设linux系统上的文件路径为 /Desktop/downloads/file_example.py
Suppose the path of the file on linux system is /Desktop/downloads/file_example.py
我通常会运行 python file_example.py
但我想设置一个cron工作,每2分钟运行python文件,位于上面的路径
But I want to set a cron job to run the python file every 2 min which is located at the above path
任何人都可以让我知道如何做
Can anyone please let me know how to do this
已修改的代码:
我已编辑代码并创建了一个bash脚本
I had edited the code and created a bash script with the name test.sh as indicated below
#!/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
推荐答案
假设您使用的是unix操作系统,您可以执行以下操作。
Assuming you are using a unix OS, you would do the following.
编辑crontab文件使用命令
edit the crontab file using the command
crontab -e
添加类似下面的行
*/2 * * * * /Desktop/downloads/file_example.py
这可以用来运行其他脚本,只需使用脚本的路径需要
this can be used to run other scripts simply use the path to the script needed i.e.
*/2 * * * * /path/to/script/to/run.sh
时间的解释如下(在数字之前添加一个星号和斜杠以运行每n个时间步,分钟)
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)
* * * * * 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)
这篇关于如何使用cron作业运行python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!