如何使用 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
谁能告诉我怎么做
编辑代码:
我编辑了代码并创建了一个名为 test.sh 的 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 个时间步运行一次,在这种情况下每 2 分钟)
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屋!