subprocess.Popen从cron

时间:2018-02-19 13:34:30

标签: python

我有下面的脚本,当我从命令行运行时,这工作正常但是当我把相同的脚本通过cron执行时,它会抛出错误。

我的代码

import subprocess
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import date as dt

sites = ('dc1', 'dc2', 'dc3')

ping_cmd = ['fping', '-C', '1']

for site in sites:

    # get_info is environment specific script which pulls certain details for the servers.
    cmd1 = ['get_info', '-c', '-H', "install%", '-s', site]
    server_list = subprocess.Popen(cmd1, stdout=subprocess.PIPE).communicate()[0].strip().split(',')
    not_alive = ''

    if len(server_list):
        for i in server_list:
            server_status = subprocess.Popen(['fping', '-C', '1', '-q', i], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out, err = server_status.communicate()
            if server_status.returncode != 0:
                not_alive += i + '\n'

current_time = dt.today().strftime("%F")
from_add = 'noreply@test.com'
to_add = 'user@test.com'

msg = MIMEMultipart()
msg['From'] = from_add
msg['To'] = to_add
msg['Cc'] = cc_add
msg['Subject'] = 'Unreachable Install Boxes on ' + current_time
# Attach the email body to MIMEMultipart object
msg.attach(MIMEText(not_alive, 'plain'))
body = msg.as_string()

server = smtplib.SMTP('localhost')
server.sendmail(from_add, [to_add, cc_add], body)
server.quit()

上面的工作正常,就像这个/usr/bin/python2 pingtest.py

一样

但是,当我在cron中安排与此08 * * * * /usr/bin/python2 /apps/rbhanot/pingtest.py相同的脚本时,我会收到以下错误

Traceback (most recent call last):
  File "/apps/nttech/rbhanot/Documents/PythonPrograms/tower-scripts/pingtest.py", line 28, in <module>
    server_list = subprocess.Popen(cmd1, stdout=subprocess.PIPE).communicate()[0].strip()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试提及环境脚本的完整路径。

<强>替换

cmd1 = ['get_info', '-c', '-H', "install%", '-s', site]

cmd1 = ['FULL_PATH/get_info', '-c', '-H', "install%", '-s', site]