简体   繁体   English

问:Python 在 Batch 中的脚本结束时停止工作

[英]Q: Python stops working at end of script in Batch

I'm running a series of python scripts from the Command window via a batch file.我正在通过批处理文件从命令窗口运行一系列 python 脚本。

Previously, it's worked without issue.以前,它可以正常工作。 However now, without a change in code, every time it gets to the end of a script I get a "Python.exe has stopped working" error.但是现在,如果没有更改代码,每次到达脚本末尾时,我都会收到“Python.exe 已停止工作”错误。 The scripts have actually completed processing, but I need to close the error window for the batch to proceed.脚本实际上已完成处理,但我需要关闭错误窗口才能继续进行批处理。

I've tried adding sys.exit to ends of the scripts but that makes no difference.我已经尝试将 sys.exit 添加到脚本的末尾,但这没有区别。 The first script has no issue but every script after has this issue.第一个脚本没有问题,但之后的每个脚本都有这个问题。

How do I stop this error from happening?如何阻止此错误发生?

Batch File批处理文件

C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script1
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script2
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script3
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4a
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4b
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4c
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4d
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script5
C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script6

the python scripts do, all, actually complete. python 脚本确实完成了所有工作。 Scripts 2-5 all use multiprocessing, however script 6 does not use multiprocessing and still experiences the error.脚本 2-5 都使用多处理,但是脚本 6 不使用多处理并且仍然遇到错误。

General Script Structure通用脚本结构

import statements
global variables
get data statements

Def Code:
    try: 
        code
        sys.exit
    except:
        print error in text file

Def multiprocessing:
    pool = multiprocessing.pool(32)
    pool.map(Code, listofData)

if main statement
    try:
        code
        multiprocessing()
        sys.exit
    except:
        print error to text file

Script 2 (the first script to error)脚本 2(第一个出错的脚本)

import arcpy, fnmatch, os, shutil, sys, traceback
import multiprocessing
from time import strftime
#===========================================================================================
ras_dir = r'C:\Path\to\Input'
working_dir = r'C:\Path\to\Output'
output_dir = os.path.join(working_dir, 'Results')
if not os.path.isdir(output_dir):
    os.mkdir(output_dir)
#===========================================================================================        
global input_files1
global raslist
global ras
raslist = []
input_files1 = []
#===========================================================================================        
for r, d, f in os.walk(working_dir):
    for inFile in fnmatch.filter(f, '*.shp'):
        input_files1.append(os.path.join(r, inFile))

for r, d, f in os.walk(ras_dir):
    for rasf in fnmatch.filter(f,'*.tif'):
        raslist.append(os.path.join(r, rasf))

ras = raslist[0]        
del rasf,raslist    

def rasextract(file):

    arcpy.CheckOutExtension("Spatial")
    arcpy.env.overwriteOutput = True
    proj = file.split('.')
    proj = proj[0] + '.' + proj[1] + '.prj'
    arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(proj)

    try:

        filename = str(file)
        filename = filename.split('\\')
        filename = filename[-1]
        filename = filename.split('.')
        filename = filename[0]

        tif_dir = output_dir + '\\' + filename
        os.mkdir(tif_dir)
        arcpy.env.workspace = tif_dir
        arcpy.env.scratchWorkspace = tif_dir

        dname = tif_dir + '\\' + filename + '_ras.tif'
        fname = working_dir+ '\\' + filename + '_ras.tif'
        bufname = tif_dir + '\\' + filename + '_rasbuf.shp'

        arcpy.Buffer_analysis(file, bufname, "550 METERS", "FULL", "ROUND", "ALL")

        newras = arcpy.sa.ExtractByMask(ras, bufname)
        newras.save(rasname)

        print "Saved " + filename + " ras"
        sys.exit


    except:
        var = traceback.format_exc()
        x = str(var)
        timecode = strftime("%a, %d %b %Y %H:%M:%S + 0000")
        logfile = open(r'C:\ErrorLogs\Log_Script2_rasEx.txt', "a+")
    ent = "\n"
        logfile.write(timecode + "             " + x + ent)
        logfile.close()

def MCprocess():
    pool = multiprocessing.Pool(32)
    pool.map(rasextract, input_files1)


if __name__ == '__main__':

    try:

        arcpy.CheckOutExtension("Spatial")  
        ras_dir = r'C:\Path\to\Input'
        working_dir = r'C:\Path\to\Output'
        output_dir = os.path.join(working_dir, 'Results')
        if not os.path.isdir(output_dir):
            os.mkdir(output_dir)
        #=============================================================      
        raslist = []
        input_files1 = []
        #=============================================================      
        for r, d, f in os.walk(working_dir):
            for inFile in fnmatch.filter(f, '*.shp'):
                input_files1.append(os.path.join(r, inFile))

        for r, d, f in os.walk(ras_dir):
            for demf in fnmatch.filter(f,'*.tif'):
                demlist.append(os.path.join(r, rasf))

        ras = raslist[0]        
        del rasf,raslist
        MCprocess()
        sys.exit

    except:
        var = traceback.format_exc()
        x = str(var)
        timecode = strftime("%a, %d %b %Y %H:%M:%S + 0000")
        logfile = open(r'C:\ErrorLogs\Log_Script2_rasEx.txt', "a+")
        ent = "\n"
        logfile.write(timecode + "             " + x + ent)
        logfile.close()

NEW error message新的错误信息

this error was encountered after disabling error reporting.禁用错误报告后遇到此错误。

在此处输入图片说明

Windows is catching the error. Windows 正在捕获错误。

Try disabling 'Window Error Reporting' in the Registry.尝试禁用注册表中的“窗口错误报告”。 After that a traceback/error should be shown.之后,应显示回溯/错误。 Here you find instructions how to disable 'WER' for Windows 10.您可以在此处找到如何为 Windows 10 禁用“WER”的说明。

Posting this as it is the only web search I could find matching my error (which was that a script ran flawlessly in IDLE, but threw the "Python has stopped working" error when called from a batch (.bat) file) - Full disclosure, I was using shelve, not using arcpy.发布此内容,因为这是我能找到的唯一匹配我的错误的网络搜索(即脚本在 IDLE 中完美运行,但在从批处理 (.bat) 文件调用时抛出“Python 已停止工作”错误) - 完全披露,我使用的是搁置,而不是使用 arcpy。

I think the issue is that you are somehow leaving files 'open', and then when the script ends Python is forced to clean up the open files in an 'unplanned' fashion.我认为问题在于您以某种方式让文件“打开”,然后当脚本结束时,Python 被迫以“计划外”的方式清理打开的文件。 Inside the IDE, this is caught and handled, but once in a batch file, the issue bubbles up to give the 'stopped working'在 IDE 中,这会被捕获并处理,但是一旦在批处理文件中,问题就会冒泡以显示“停止工作”

contrast:对比:

f = open("example.txt", "r")

with

f = open("example.txt", "r")
f.close()

The first will error out from a bat file, the second will not.第一个会从 bat 文件中出错,第二个不会。

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

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