繁体   English   中英

当任务计划程序调用时,Python脚本无法正常工作

[英]Python script not working as intended when called by task scheduler

我是Python和这个网站的初学者。 抱歉,这可能很简单。

我修改了一个python脚本,该脚本计算pdf文件“ Master.pdf”中的单词数量,然后将时间和日期以及单词数量写入.txt文件。

我已经安装了Python2.7,已经安装了Anancoda,并且正在使用PyCharm编辑器。 当我打开PyCharm编辑器并运行此脚本时,不会出现任何问题,脚本将执行并且一切正常。

因为我希望此脚本每15分钟运行一次,所以我已使用Task Scheduler将其作为一项任务。 任务是“启动程序”,程序是:-C:\\ Users \\ alkare \\ AppData \\ Local \\ Continuum \\ anaconda2 \\ python.exe-参数是-“ C:/ Users / alkare / Desktop / Report / WordCount .py”-。

每当它运行时,我都会看到命令提示符打开,屏幕上飞来一些文本,然后命令行终端关闭,但是对.txt文件未做任何更改。

这是我使用的代码另存为“ WordCount.py”:

#!/usr/bin/env python2.7
import os
import sys
import re
import datetime
import PyPDF2

def getPageCount(pdf_file):
    pdfFileObj = open(pdf_file, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    pages = pdfReader.numPages
    return pages


def extractData(pdf_file, page):
    pdfFileObj = open(pdf_file, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    pageObj = pdfReader.getPage(page)
    data = pageObj.extractText()
    return data


def getWordCount(data):
    data = data.split()
    return len(data)


def main():
    pdfFile = 'Master.pdf'

    # get the word count in the pdf file
    totalWords = 0
    numPages = getPageCount(pdfFile)
    for i in range(numPages):
        text = extractData(pdfFile, i)
        totalWords += getWordCount(text)
        Now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    f = open("TrackingTimeData.txt", "a")
    f.write(Now[0:4] + "\t" + Now[4:6] + "/" + Now[6:8] + "\t" + Now[9:11] + ":" + Now[11:13] + "\t" + str(totalWords) + "\n")
    f.close()


if __name__ == '__main__':
    main()

问题是您允许程序失败而没有提供任何有意义的输出(听起来像是遇到了异常并关闭了)。

而不是只在没有try块的情况下调用main():

if __name__ == '__main__':
    main()

在这里给自己一些时间来收集信息:

if __name__ == '__main__':
    try:    
        main()
    except Exception as e:
        print("Error {}".format(e))
        # drop into a command-prompt debugger:
        import pdb
        pdb.set_trace()

        # slightly more old-school, pause the window to read the exception:            
        import time
        time.sleep(15)

        # throwback to DOS windows
        import os
        os.system('pause')

        # read the error, come back to stackoverflow and describe the problem more, etc.

例如,将其与任务计划程序混合使用,您想在Windows中右键单击python.exe,转到属性,设置“以管理员身份运行”,因为可能是您拒绝尝试读取/写入对文件的访问权限.PDF在某些特殊目录中。 这只是人们可能会随机猜测的许多示例,它们可以帮助您解决问题而不是确切地知道错误是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM