首页 > 解决方案 > Python将记录插入到另一个批处理作业使用的日志文件中

问题描述

我面临一个特殊的问题。我有一个批处理脚本,它使用名为 logfile.txt 的日志文件。本质上,这个批处理作业只不过是一系列xcopy运行如下的 python 文件:

xcopy /I "source" "destination /D" >> D:\logfile\logfile.txt
xcopy /I "source" "destination /D" >> D:\logfile\logfile.txt
....
cd C:\ProgramData\Anaconda3
pyhton D:\python_files\py_file_1.py >> D:\logfile\logfile.txt
python D:\python_files\py_file_2.py >> D:\logfile\logfile.txt
....

现在我想提两件事。我的问题与这两点一致。

  1. 虽然我可以看到xcopy相关内容显示在日志文件中(即复制的文件数),但没有运行 python 作业的日志条目。为什么这样?
  2. 我有另一个 python 脚本(如下所示),它填充了另一个名为 .txtpy_log.txt的文件,以防在运行上述 py 文件时发生任何错误。如果没有错误,则插入标准行。我想将这些错误条目或标准条目插入到批处理logfile.txt中。

    lines = []
    with open('py_log.txt','r') as f_in:
         z = str(f_in)
         lines.append(z)
    with open('logfile.txt', 'a') as f_out:    
         if len(lines) > 1:
             f_out.write('\n'+lines) # Error Entry if Any
         else:
             f_out.write('\n'+'Data load job has been completed at {0}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H-%M')
    

问题是,当我在任务计划程序上安排上述 python 脚本时,它不会向 logfile.txt 插入任何文本。当我独立运行它时,它工作正常。

为什么将上面的脚本放在任务计划程序上时无法编写。我错过了什么?

标签: pythonbatch-file

解决方案



推荐阅读