Crontab上的Python不执行bash脚本

时间:2018-12-06 12:33:25

标签: python bash cron

import subprocess as sub
import re
import os
from datetime import datetime as influx_timestap
from influxdb import InfluxDBClient
from collections import OrderedDict

insert_json = []
hostname = str(sub.check_output('hostname')).strip()
location = str(sub.check_output(['ps -ef | grep mgr'], shell=True)).split()
current_dir = os.getcwd()
print("script executed")
gg_location_pattern = re.compile(r'mgr\.prm$')
gg_process_pattertn = re.compile(r'^REPLICAT|^EXTRACT')
for index in location:
    if gg_location_pattern.search(index) != None:
        gg_location = index[:-14]

os.chdir(gg_location)
print("checkpoint1")
get_lag = sub.check_output(str(current_dir) + '/ggsci_test.sh', shell=True)
print("checkpoint2")
processes = get_lag.split("\n")

for process in processes:
    if gg_process_pattertn.search(process) != None:
        lag_at_chkpnt = int((process.split()[3]).split(":")[0]) * 3600 + int((process.split()[3]).split(":")[1]) *60 + int((process.split()[3]).split(":")[2])
        time_since_chkpnt = int((process.split()[4]).split(":")[0]) * 3600 + int((process.split()[4]).split(":")[1]) *60 + int((process.split()[4]).split(":")[2]
)
        process_dict = OrderedDict({"measurement": "GoldenGate_Mon_" + str(hostname) +  "_Graph",
                        "tags": {"hostname": hostname, "process_name": process.split()[2]},
                        "time": influx_timestap.now().isoformat('T'),
                        "fields": {"process_type": process.split()[0], "process_status": process.split()[1],
                        "lag_at_chkpnt": lag_at_chkpnt, "time_since_chkpnt": time_since_chkpnt}})
        insert_json.append(process_dict)


host = 'xxxxxxxx'
port = 'x'
user = 'x'
password = 'x'
dbname = 'x'
print("before client")
client = InfluxDBClient(host, port, user, password, dbname)
client.write_points(insert_json)
print("after client")

此代码可以手动完美运行,但是在crontab上却无法运行。在互联网上搜索后,我发现他们说在crontab上更改或设置了您的“ PATH”变量。我更改了“ PATH”变量,但仍无法正常工作。

Crontab日志文件写完“ checkpoint1”之后,什么都没有了。因此,行不起作用是"get_lag = sub.check_output(str(current_dir) + '/ggsci_test.sh', shell=True)"

此后我该怎么办? 保重,

1 个答案:

答案 0 :(得分:0)

您的外部脚本(ggsci_test.sh)似乎在路径/一般故障方面有问题。

Python subprocess documentation关于subprocess.check_output

  

如果返回码非零,则引发CalledProcessError。的   CalledProcessError对象的返回码中将包含返回码   属性以及输出属性中的所有输出。

因此,这就是您在捕获错误时看到错误但无法继续的原因。

因此,您应该检查您的shell脚本是否有任何需要先解决的问题。