簡體   English   中英

Python 腳本不會從 .bat 文件、任務計划程序或 cmd 提示符運行

[英]Python script won't run from .bat file, Task Scheduler, or cmd prompt

我有一個 Python 腳本,它在從 Eclipse、IDLE 運行時效果很好,雙擊目錄文件夾中的 .py 文件。 我需要自動執行此操作以每晚運行,但無法從 Windows 任務計划程序運行它,因此我編寫了一個 .bat 文件,但它也不起作用。

蟒蛇腳本:

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 . . .

我已將雙 \\ 刪除為單個 \\ 但這也不起作用。 任何建議將不勝感激。

謝謝!

考慮在所有文件中指定一個絕對路徑。 目前,在您的外部文件的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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM