Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

shell - How to run a python file using cron jobs

Hi I have created a python file for example as file_example.py

The file will output the sensex value

Suppose the path of the file on linux system is /Desktop/downloads/file_example.py

and I normally will run the file like 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

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

#!/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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you are using a unix OS, you would do the following.

edit the crontab file using the command

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 i.e.

*/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)

* * * * * 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...