gpt4 book ai didi

Python crontab 尝试除 ValueError

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:59 25 4
gpt4 key购买 nike

我有这个脚本,当我从命令行运行时它工作正常...

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
from time import sleep
import os
import logging
import glob
import sys
import subprocess
import pymssql
import shutil
import StringIO
from StringIO import StringIO

#Check share mounted
if os.path.ismount("/home/marco/cas01-share/") == 0:

#logging.info('share not mounted')
print "share not mounted"
#mount share
#logging.info('share now mounted')
#print "share now mounted"
else:
print "share mounted"

# File paths
fullpath2Newfile = "/home/marco/cas01-share/New/"
fullpathfiles2Process = "/home/marco/cas01-share/Process/"
fullpathProcessedfiles = "/home/marco/cas01-share/Processed/"

if not os.listdir('/home/marco/cas01-share/New'):
print "directory empty"
else:
print "directory not empty"

# Directory more than one file?
num_files = len([f for f in os.listdir('/home/marco/cas01-share/New')
if os.path.isfile(os.path.join('/home/marco/cas01-share/New', f))])
print "directory has " + str(num_files) + " files"



num_files = 0

for filename in os.listdir('/home/marco/cas01-share/New'):
succesfullRun = 0
num_files += 1

print filename
filename = str(filename)
batchnumber = filename.strip("['SENSE-extract-ascii--.csv']")[:-9]
print batchnumber

newfullpath2Newfile = fullpath2Newfile + filename
fullpathfiles2Process = "/home/marco/cas01-share/Process/SENSE-extract.csv"
fullpathProcessedfiles = "/home/marco/cas01-share/Processed/SENSE-extract-" + batchnumber + ".csv"
print newfullpath2Newfile
print fullpathfiles2Process
print fullpathProcessedfiles


# Execute job
ExceptionFlag = 0
while (succesfullRun == 0):

if ExceptionFlag == 0:
shutil.move(newfullpath2Newfile, fullpathfiles2Process)

try:

# Move to sense check folder
# Connect to DB
conn = pymssql.connect(server='IP', user='User', password='password', tds_version='8.0')
cursor = conn.cursor()
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = 'Marco_test'")

except Exception as e:
(error_code, error_message) = e

ExceptionFlag = 1

#print error_message

if "does not exist" in error_message:
print "ERROR: Job name not found"

if "job is already running" in error_message:
print "ERROR: a Job is already running"

if "job already has a pending request" in error_message:
print "ERROR: pending request"

time.sleep(0.5)

else:
print "Job executed succesfully"
# Copy file to processed
shutil.copy(fullpathfiles2Process, fullpathProcessedfiles)

succesfullRun = 1

conn.close()
time.sleep(0.5)

exit()

但是当我尝试在 crontab 上安排时,出现以下错误

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command

#SENSE
*/5 * * * * /usr/bin/python /home/administrator/Share/scripts/python3 >> /home/administrator/Share/scripts/logs/sense$

我收到这个错误:

Traceback (most recent call last): File "...", line 239, in (error_code, error_message) = e ValueError: need more than 1 value to unpack

我认为这与“cronos 计划执行作业”和它自己的脚本之间没有管道有关,我不知道这是否有意义,就像它不知道从哪里获取信息一样......

本质上是试图捕获 EXECUT a MSSQL JOB 命令的异常。

最佳答案

您的问题是您正在解包异常。不应假定异常是可迭代的,也不应假定它们包含参数。

In [2]: try:
...: assert False
...: except Exception as e:
...: c, m = e
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-2e0dd0160822> in <module>()
2 assert False
3 except Exception as e:
----> 4 c, m = e
5

ValueError: need more than 0 values to unpack

如果您将消息传递给 Exception 类,则它具有 1 个值:

In [3]: try:
assert False, "This is a message"
except Exception as e:
c, m = e
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-8af2ea044375> in <module>()
2 assert False, "This is a message"
3 except Exception as e:
----> 4 c, m = e
5

ValueError: need more than 1 value to unpack

您的错误处理固有地会在错误捕获后产生错误。学习使用回溯或 Exception.args 代替:

回溯示例

In [10]: try:
....: assert False, "This is a message"
....: except Exception as error:
....: trace = traceback.format_exc()
....: print(trace, file=sys.stderr)
....:
Traceback (most recent call last):
File "<ipython-input-10-5a56c0f9112a>", line 2, in <module>
assert False, "This is a message"
AssertionError: This is a message

Exception.args 示例

In [11]: from __future__ import print_function

In [12]: import sys

In [13]: try:
....: assert False, "This is a message"
....: except Exception as error:
....: print(error.args, file=sys.stderr)
....:
('This is a message',)

关于Python crontab 尝试除 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com