简体   繁体   English

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

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

I have a Python script which works great when running from Eclipse, IDLE, double clicking on the .py file in the directory folder.我有一个 Python 脚本,它在从 Eclipse、IDLE 运行时效果很好,双击目录文件夹中的 .py 文件。 I need to automate this to run every night but I cannot get it to run from the Windows Task Scheduler so I've written a .bat file and it does not work either.我需要自动执行此操作以每晚运行,但无法从 Windows 任务计划程序运行它,因此我编写了一个 .bat 文件,但它也不起作用。

Python script:蟒蛇脚本:

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)

Current .bat file:当前 .bat 文件:

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

CMD output from above .bat file (this output is expected but the .xml and .csv files are never created from .bat): .bat 文件上方的 CMD 输出(此输出是预期的,但 .xml 和 .csv 文件从未从 .bat 创建):

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

Previous .bat files that didn't work:以前不起作用的 .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

Here is the error message:这是错误消息:

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

I've removed the double \\ to a single \\ but that didn't work either.我已将双 \\ 删除为单个 \\ 但这也不起作用。 Any suggestions would be greatly appreciated.任何建议将不胜感激。

Thanks!谢谢!

Consider designating an absolute path in all files.考虑在所有文件中指定一个绝对路径。 Currently, in open() of your external files, relative paths are assumed which will be problematic if batch files and command lines are run externally.目前,在您的外部文件的open()中,假设相对路径,如果批处理文件和命令行在外部运行,这将是有问题的。

Try saving .xml and .csv files to current path of .py script and any call to .py (IDEs or command line) will use such an absolute path.尝试将 .xml 和 .csv 文件保存到 .py 脚本的当前路径,任何对 .py(IDE 或命令行)的调用都将使用这样的绝对路径。 Below uses the os.path.join() to concatenate directory and file names.下面使用os.path.join()来连接目录和文件名。 This function is platform agnostic (Windows, Mac, Linux) and avoids the back or forward slash needs and works in deployment to other users as no hard-coded paths are set.此功能与平台无关(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.

相关问题 批处理文件中的Python脚本无法在任务计划程序中运行 - Python script from batch file won't run in task scheduler 任务调度器+python+bat文件 - Task scheduler +python + bat file Python脚本无法在bash脚本中运行,但在cmd提示符下可以正常工作 - Python script won't run in bash script, but works fine in cmd prompt 任务计划程序打开命令提示符但不运行 python 脚本 - Task Scheduler opens command prompt but does not run python script Task Scheduler不会运行python脚本(pywin32)来打开Excel。 如何从Pywin32获取更多信息 - Task scheduler won't run python script (pywin32) to open Excel. How to get more info from Pywin32 通过任务计划程序运行时,Python脚本未创建文件 - Python Script not creating file when run through Task Scheduler 从 Edge 下载文件时,如何在 Windows 任务计划程序中运行 Python 脚本? - How to run a Python script in Windows Task Scheduler when a file is downloaded from Edge? 我的 Python 脚本无法从任务计划程序运行 - My Python Script does not run from Task Scheduler Task Scheduler启动的Python脚本无法编辑文件 - Python script started by Task Scheduler can't edit file 从任务调度程序运行 python 脚本作为任务 - Running a python script as task from task scheduler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM