Linux 通过 crontab 执行 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8727935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute Python script via crontab
提问by guisantogui
I'm trying to execute a python script using the Linux crontab. I want to run this script every 10 minutes.
我正在尝试使用 Linux crontab 执行 python 脚本。我想每 10 分钟运行一次这个脚本。
I found a lot of solutions and none of them work. For example: edit the anacron at /etc/cron.d or use crontab -e
. I put this line at the end of the file, but it doesn't change anything. Do I have to restart any service(s)?
我找到了很多解决方案,但没有一个有效。例如:在 /etc/cron.d 编辑 anacron 或使用crontab -e
. 我把这一行放在文件的末尾,但它没有改变任何东西。我是否必须重新启动任何服务?
*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py
What file must I edit to configure this?
我必须编辑什么文件来配置它?
Thanks in advance
提前致谢
Here is the script.
这是脚本。
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import json
import os
import pycurl
import sys
import cStringIO
if __name__ == "__main__":
name_server_standart = "Server created by script %d"
json_file_standart = "{ \"server\" : { \"name\" : \"%s\", \"imageRef\" : \"%s\", \"flavorRef\" : \"%s\" } }"
curl_auth_token = pycurl.Curl()
gettoken = cStringIO.StringIO()
curl_auth_token.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1")
curl_auth_token.setopt(pycurl.POST, 1)
curl_auth_token.setopt(pycurl.HTTPHEADER, ["X-Auth-User: cpca",
"X-Auth-Key: 438ac2d9-689f-4c50-9d00-c2883cfd38d0"])
curl_auth_token.setopt(pycurl.HEADERFUNCTION, gettoken.write)
curl_auth_token.perform()
chg = gettoken.getvalue()
auth_token = chg[chg.find("X-Auth-Token: ")+len("X-Auth-Token: ") : chg.find("X-Server-Management-Url:")-1]
token = "X-Auth-Token: {0}".format(auth_token)
curl_auth_token.close()
#----------------------------
getter = cStringIO.StringIO()
curl_hab_image = pycurl.Curl()
curl_hab_image.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/images/7")
curl_hab_image.setopt(pycurl.HTTPGET, 1) #tirei essa linha e funcionou, nao sei porque
curl_hab_image.setopt(pycurl.HTTPHEADER, [token])
curl_hab_image.setopt(pycurl.WRITEFUNCTION, getter.write)
#curl_list.setopt(pycurl.VERBOSE, 1)
curl_hab_image.perform()
curl_hab_image.close()
getter = cStringIO.StringIO()
curl_list = pycurl.Curl()
curl_list.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/servers/detail")
curl_list.setopt(pycurl.HTTPGET, 1) #tirei essa linha e funcionou, nao sei porque
curl_list.setopt(pycurl.HTTPHEADER, [token])
curl_list.setopt(pycurl.WRITEFUNCTION, getter.write)
#curl_list.setopt(pycurl.VERBOSE, 1)
curl_list.perform()
curl_list.close()
#----------------------------
resp = getter.getvalue()
con = int(resp.count("status"))
s = json.loads(resp)
lst = []
for i in range(con):
lst.append(s['servers'][i]['status'])
for j in range(len(lst)):
actual = lst.pop()
print actual
if actual != "ACTIVE" and actual != "BUILD" and actual != "REBOOT" and actual != "RESIZE":
print "Entra no If"
f = file('counter', 'r+w')
num = 0
for line in f:
num = line
content = int(num)+1
ins = str(content)
f.seek(0)
f.write(ins)
f.truncate()
f.close()
print "Contador"
json_file = file('json_file_create_server.json','r+w')
name_server_final = name_server_standart % content
path_to_image = "http://192.168.100.241:8774/v1.1/nuvemcpca/images/7"
path_to_flavor = "http://192.168.100.241:8774/v1.1/nuvemcpca/flavors/1"
new_json_file_content = json_file_standart % (name_server_final, path_to_image, path_to_flavor)
json_file.seek(0)
json_file.write(new_json_file_content)
json_file.truncate()
json_file.close()
print "Json File"
fil = file("json_file_create_server.json")
siz = os.path.getsize("json_file_create_server.json")
cont_size = "Content-Length: %d" % siz
cont_type = "Content-Type: application/json"
accept = "Accept: application/json"
c_create_servers = pycurl.Curl()
logger = cStringIO.StringIO()
c_create_servers.setopt(pycurl.URL, "http://192.168.100.241:8774/v1.1/nuvemcpca/servers")
c_create_servers.setopt(pycurl.HTTPHEADER, [token, cont_type, accept, cont_size])
c_create_servers.setopt(pycurl.POST, 1)
c_create_servers.setopt(pycurl.INFILE, fil)
c_create_servers.setopt(pycurl.INFILESIZE, siz)
c_create_servers.setopt(pycurl.WRITEFUNCTION, logger.write)
print "Teste perform"
c_create_servers.perform()
print logger.getvalue()
c_create_servers.close()
采纳答案by Raul Marengo
回答by Basile Starynkevitch
Put your script in a file foo.py
starting with
将您的脚本放在一个foo.py
以
#!/usr/bin/python
then give execute permission to that script using
然后使用该脚本授予执行权限
chmod a+x foo.py
and use the full path of your foo.py
file in your crontab
.
并foo.py
在crontab
.
See documentation of execve(2)which is handling the shebang
请参阅处理shebang的execve(2) 的文档
回答by greenqy
As you have mentioned doesn't changes anything,
正如你所提到的不会改变任何东西,
First, you should redirect both stdin and stderr from crontab execution like below:
首先,您应该从 crontab 执行重定向 stdin 和 stderr,如下所示:
*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1
then you can view the file /tmp/listener.log
to see if the script executed as you expect.
然后您可以查看文件/tmp/listener.log
以查看脚本是否按预期执行。
Second, guess what you mean change anythingis by watching the files created by your program:
其次,猜测你的意思是通过观察你的程序创建的文件来改变任何东西:
f = file('counter', 'r+w')
json_file = file('json_file_create_server.json','r+w')
the crontab job above won't create these file in directory /home/souza/Documets/Listener
, as the cron job is not executed in this directory, and you use relative path in the program. So to create these file in directory /home/souza/Documets/Listener
, the following cron job will do the trick:
上面的 crontab 作业不会在目录中创建这些文件/home/souza/Documets/Listener
,因为 cron 作业不在此目录中执行,并且您在程序中使用相对路径。因此,要在 directory 中创建这些文件/home/souza/Documets/Listener
,以下 cron 作业将起作用:
*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1
Change to the working directory and execute the script from there, then you can view the files created in place.
切换到工作目录并从那里执行脚本,然后您可以查看就地创建的文件。