在任务调度程序调用时,Python脚本无法正常工作

时间:2017-10-23 09:43:02

标签: python taskscheduler

我是Python和本网站的初学者。对不起,如果这可能很简单。

我修改了一个python脚本来计算pdf文件中的单词数量" Master.pdf" a将时间和日期加上单词的数量写入.txt文件。

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

由于我希望此脚本每15分钟运行一次,因此我使用任务计划程序将其作为一项任务。任务是"启动一个程序"该计划是: - 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()

1 个答案:

答案 0 :(得分:1)

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

而不是仅在调用main()而不在try块中保护它:

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。这只是众多猜测的一个例子,人们可以随机帮助您解决问题,而不是确切地知道错误是什么。

相关问题