Python脚本不会从.bat文件,任务计划程序或cmd提示符运行

时间:2016-04-25 22:58:44

标签: python batch-file

我有一个Python脚本,当从Eclipse运行,IDLE,双击目录文件夹中的.py文件时效果很好。我需要自动执行此操作以便每晚运行,但我无法让它从Windows任务计划程序运行,所以我写了一个.bat文件,它也不起作用。

Python脚本:

import urllib.request
import time
from lxml import etree
import datetime
import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

today = datetime.date.today()
ts = int(time.time()) - 86400
tsend = int(time.time())
#ts = 1461253877
#tsend = 1461340277

dailyReport = "URL_GOES_HERE".format(ts, tsend)

with urllib.request.urlopen(dailyReport) as url:
    soup = url.read()
saveFile = open('{}_dailyIdleReport.xml'.format(today),'wb')
saveFile.write(soup)
saveFile.close()

tree = etree.parse('{}_dailyIdleReport.xml'.format(today))
root = tree.getroot()
print(root.tag, root.attrib)

zonarFile = open('{}_idleReport.csv'.format(today),'w', newline='')
outputWriter = csv.writer(zonarFile)
outputWriter.writerow(['Asset ID', 'Event Type', 'Idle Length', 'Cost'])

for assetidle in root.findall('assetidle'):
    for element in assetidle:
        for event in assetidle.findall('event'):
            fleet = assetidle.get('fleet')
            eventtype = event.get('type')
            length = event.find('length').text
            tlength = length
            (h, m, s) = tlength.split(':')
            result = ((float(h)/1) + (float(m)/60) + (float(s)/3600))
            cost = (result * 1.5) * 1.80
            displayCost = '${:,.2f}'.format(cost)            
            zonarFile = open('{}_idleReport.csv'.format(today),'a', newline='')
            outputWriter = csv.writer(zonarFile)
            outputWriter.writerow([fleet,eventtype,length,displayCost])
            zonarFile.close()            
            #print('Asset #:  %s  %s  %s  %s' %(fleet,eventtype,length,displayCost))

fromaddr = "myemail@server.com"
toaddr = "myemail@server.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "The Zonar %s" %'{}_idleReport.csv'.format(today)
body = "The Zonar Daily Idle Report is attached."

filename = "{}_idleReport.csv".format(today)
attachment = open("C:\\Users\\PeggyBall\\workspace\\ZonarCSCProject\\src\\{}_idleReport.csv".format(today), "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
body = "The Zonar Idle Report for {} is attached.".format(today)
msg.attach(MIMEText(body, 'plain'))
msg.attach(part)

server = smtplib.SMTP('smtp.email.serverhere', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("email_username", "email_password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

当前的.bat文件:

@echo off
c:\Users\PeggyBall\AppData\Local\Programs\Python\Python35\python.exe c:\Users\PeggyBall\workspace\ZonarCSCProject\src\DailyIdleReport.py
pause

来自.bat文件的CMD输出(此输出是预期的,但.xml和.csv文件永远不会从.bat创建):

eventlist {'end': '1461716317', 'ver': '1', 'count': '38', 'start': '1461629917'}
Press any key to continue . . .

以前无效的.bat文件:

@echo off
C:\Users\PeggyBall\workspace\ZonarCSCProject\src\DailyIdleReport.py %*
pause

@echo off
C:\Users\PeggyBall\AppData\Local\Programs\Python\Python35\python.exe C:\Users\PeggyBall\workspace\ZonarCSCProject\src\DailyIdleReport.py %*
pause

以下是错误消息:

eventlist {'ver': '1', 'end': '1461624597', 'count': '33', 'start': '1461538197'}
Traceback (most recent call last):
  File "C:\Users\PeggyBall\workspace\ZonarCSCProject\src\DailyIdleReport.py", line 68, in <module>
    attachment = open("C:\\Users\\PeggyBall\\workspace\\ZonarCSCProject\\src\\idleReport.csv","rb")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\PeggyBall\\workspace\\ZonarCSCProject\\src\\idleReport.csv'
Press any key to continue . . .

我已将双\ \删除为单个\但这也不起作用。任何建议都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

考虑在所有文件中指定绝对路径。目前,在open()的外部文件中,假设相对路径在批量文件和命令行在外部运行时会出现问题。

尝试将.xml和.csv文件保存到.py脚本的当前路径,并且对.py(IDE或命令行)的任何调用都将使用这样的绝对路径。下面使用os.path.join()来连接目录和文件名。此功能与平台无关(Windows,Mac,Linux),可避免后向或正向斜线需求,并可在部署到其他用户时工作,因为未设置硬编码路径。

import os
...

# CURRENT DIRECTORY OF RUNNING SCRIPT
cd = os.path.dirname(os.path.abspath(__file__))

# EXTERNAL FILE NAMES
xmlfile = os.path.join(cd, '{}_dailyIdleReport.xml'.format(today))
csvfile = os.path.join(cd, '{}_idleReport.csv'.format(today))

with urllib.request.urlopen(dailyReport) as url:
    soup = url.read()
saveFile = open(xmlfile, 'wb')
saveFile.write(soup)
saveFile.close()

tree = etree.parse(xmlfile)
root = tree.getroot()
print(root.tag, root.attrib)

zonarFile = open(csvfile,'w', newline='')
outputWriter = csv.writer(zonarFile)
outputWriter.writerow(['Asset ID', 'Event Type', 'Idle Length', 'Cost'])

for assetidle in root.findall('assetidle'):
    for element in assetidle:
        for event in assetidle.findall('event'):
            ...
            zonarFile = open(csvfile, 'a', newline='')

...
# ATTACHMENT
attachment = open(csvfile, "rb")
相关问题