如何知道进程是否仍在Python中运行?

如何知道进程是否仍在Python中运行?,python,process,Python,Process,我对此做了一些研究,但所有的问题(在我的新手理解中)似乎都是关于如何判断是否有另一个程序在运行,而不是Python本身 因此,我目前正在编写一个代码,该代码围绕shapefile中的一组行生成缓冲区。这是一个批处理过程,涉及20个shapefile,其中多达4000行。这个过程花了很长时间,我开始怀疑它是否真的有效。 我通常使用print语句来跟踪代码的进度,但在本例中,我调用ArcGIS来执行该功能,因此我可以编写的唯一print语句是在处理完所有行之后编写的,而不是在它仍在运行时编写的 是否

我对此做了一些研究,但所有的问题(在我的新手理解中)似乎都是关于如何判断是否有另一个程序在运行,而不是Python本身

因此,我目前正在编写一个代码,该代码围绕shapefile中的一组行生成缓冲区。这是一个批处理过程,涉及20个shapefile,其中多达4000行。这个过程花了很长时间,我开始怀疑它是否真的有效。 我通常使用print语句来跟踪代码的进度,但在本例中,我调用ArcGIS来执行该功能,因此我可以编写的唯一print语句是在处理完所有行之后编写的,而不是在它仍在运行时编写的

是否有任何方法可以确定流程是否仍在进行(除了检查任务管理器以查看其是否已冻结)

我想到了一种疯狂的方式(不知道这样的事情是否可能):我想的是,只要脚本还没有运行完,每隔X分钟在txt文件中写入一些东西

谢谢

我的代码:

def Buffer30m(self,InputFile,OutputBuffer, size):    
   arcpy.Buffer_analysis(InputFile,OutputBuffer,size,"FULL","ROUND","NONE","#")


TheList=os.listdir(SSFlinespath)    #read the files in the folder
os.mkdir(SSFlines+"SSFbuffers"      #create folder for the output
SSbuff=SSFlinespath+"SSFbuffers/"   #select the folder as destination 
try:
    size=30
    for TheFile in TheList:                                          #Identify each file
        TheFileName, TheFileExtension = os.path.splitext(TheFile)    #Break up the file name
        if (TheFileExtension==".shp"):                               #Identify the shapefiles
            TheLines=SSFlines+TheFile
            ##Generate a 30m buffer around the lines
            TheBuffer=SSFbuff+TheFileName+"_buff30.shp"
            TheStepBuffer.Buffer30m(TheLines,TheBuffer,size)
            print "SSF buffer done"  
 except Exception as TheError:
    print "Error with the SSF forest area calculation"
    print TheError

更新 部分解决方案、完整代码和新问题:

我应用了qwwqwwq的建议,这对我前面提到的函数非常有用。现在的问题是,当我运行脚本的其余部分时(我之前展示的只是脚本的一部分,因此您不必阅读太多),其他一些函数不起作用

以下是完整的脚本:

class StepBuffer:
 def GetPairInfo (self, MainFile, SourceFile, WantFields, SSF):
    fields= WantFields   #Fields I will keep
    ##Extract the info and add to the main table
    if SSF==False:
        GRHE_proj.GetFieldInfo(MainFile,SourceFile,"Pair", "Pair", fields)
    elif SSF==True:
        GRHE_proj.GetFieldInfo(MainFile,SourceFile,"SAMPLEID", "SAMPLEID", fields)

 def Buffer30m(self,InputFile,OutputBuffer, size):
    arcpy.Buffer_analysis(InputFile,OutputBuffer,size,"FULL","ROUND","NONE","#")

 def AreaBuff (self,InputFile, OutputTable):      
    arcpy.CalculateAreas_stats(InputFile,OutputTable)

 def AreaForest (self,BufferFile,ForestFile, OutputTable, SSF):
    if SSF==False:
        arcpy.TabulateIntersection_analysis(BufferFile,"Pair",ForestFile,OutputTable,"type","#","#","HECTARES")
    elif SSF==True:
        arcpy.TabulateIntersection_analysis(BufferFile,"SAMPLEID",ForestFile,OutputTable,"type","#","#","HECTARES")



TheList=os.listdir(SSFlinespath)    #read the files in the folder
os.mkdir(SSFlines+"SSFbuffers"      #create folder for the output
SSbuff=SSFlinespath+"SSFbuffers/"   #select the folder as destination

try:
    size=30
    for TheFile in TheList:                                          #Identify each file
    TheFileName, TheFileExtension = os.path.splitext(TheFile)    #Break up the file name
    if (TheFileExtension==".shp"):                               #Identify the shapefiles
        TheLines=SSFlines+TheFile
        ##Generate a 30m buffer around the lines
                t = threading.Thread(target=TheStepBuffer.Buffer30m, args=(TheLines,TheBuffer,size))
                t.start() 
                while (t.is_alive()):
                    time.sleep(2)  ## sleep so that we don't execute the print statement too often
                    print "I'm alive!"                  
                print "SSF buffer done"


                ##Calculate area of buffer
                TableAreaBuff=OutputTables+TheFileName+"_Area_Buffers.dbf"         
                TheStepBuffer.AreaBuff(TheBuffer,TableAreaBuff)
                print "SSF area buffer done"

                ##Calculate the area of the forest inside the buffer
                TableAreaFor=OutputTables+TheFileName+"_Area_forest.dbf"
                TheStepBuffer.AreaForest(TheBuffer,ForestPath,TableAreaFor,True)
                print "SSF area forest done"

                ##Add info of the area of the buffer to the buffer layer
                TheStepBuffer.GetPairInfo(TheBuffer,TableAreaBuff, "F_AREA",True)

                ##Add info of area of forest within the buffers to the buffer layer
                TheStepBuffer.GetPairInfo(TheBuffer,TableAreaFor,["Area","Percentage"],True)
                print TheFileName+"Done"
    except Exception as TheError:
        print "Error with the SSF forest area calculation"
        print TheError
        TheErrorFile.writelines(format(TheError)+"\n")
具体而言,当出现以下情况时,会出现错误:

TheStepBuffer.AreaForest(TheBuffer,ForestPath,TableAreaFor,True)
产生此错误:

arcgisscripting.ExecuteError:
Traceback (most recent call last):
File "c:\program files (x86)\arcgis\desktop10.1\
ArcToolbox\Scripts\CalculateAreas.py", line 76, in <module>
setupCalcAreas()
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py", line 31, in setupCalcAreas
calculateAreas(inputFC, outputFC)
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py", line 55, in calculateAreas
cnt = UTILS.getCount(inputFC)
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\SSUtilities.py", line 502, in getCount
return int(countObject.getOutput(0))
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\arcobjects.py", line 986, in getOutput ... (truncated)
return convertArcObjectToPythonObject(self._arc_object.GetOutput(*gp_fixargs(args))) ... (truncated)
File "C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python_Codes\Scripts\MovementPref\volpe_project_v2.py", line 464, in <module>
  TheStepBuffer.AreaBuff(TheBuffer,TableAreaBuff)
File "C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python_Codes\ReUsable\Movement_preferences.py", line 58, in AreaBuff
  arcpy.CalculateAreas_stats(InputFile,OutputTable)
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\stats.py", line 1564, in CalculateAreas
  raise e
arcgisscripting.ExecuteError:
回溯(最近一次呼叫最后一次):
文件“c:\program files(x86)\arcgis\desktop10.1\
ArcToolbox\Scripts\CalculateAreas.py”,第76行,在
设置区域()
文件“c:\program files(x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py”,第31行,在SetupCalCaraAreas中
计算区域(输入FC、输出FC)
CalculateAreas中的文件“c:\program files(x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py”,第55行
cnt=UTILS.getCount(inputFC)
getCount中第502行的文件“c:\program files(x86)\arcgis\desktop10.1\ArcToolbox\Scripts\sUtility.py”
返回int(countObject.getOutput(0))
文件“C:\Program Files(x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\arcobjects.py”,第986行,在getOutput中。。。(截断)
返回convertArcObjectToPythonObject(self.\u arc\u object.GetOutput(*gp\u fixargs(args)))。。。(截断)
文件“C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python\u code\Scripts\MovementPref\Volpe\u Project\u v2.py”,第464行,在
StepBuffer.AreaBuff(缓冲区,TableAreaBuff)
文件“C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python\u Codes\reusables\Movement\u preferences.py”,第58行,在AreaBuff中
arcpy.CalculateAreas_统计(输入文件,可输出)
文件“C:\Program Files(x86)\ArcGIS\Desktop10.1\arcpy\arcpy\stats.py”,第1564行,在CalculateAreas中
提高e
有人知道这个错误的来源吗?
谢谢

我会尝试使用多线程:

import threading
import time
t = threading.Thread(target=TheStepBuffer.Buffer30m, args=(TheLines,TheBuffer,size))
t.start()

while (t.is_alive()):
    time.sleep(2)  ## sleep so that we don't execute the print statement too often
    print "I'm alive!"

线程将执行函数
步骤缓冲区.Buffer30m
,控制线程将监视该线程,以确保它仍在执行目标函数,执行
print
语句,让您知道一切都很好。

您应该遵循变量名称的规则-坚持使用带有下划线的
小写字母\u
而不是
大写字母
-此命名约定用于类,可能会混淆其他类。哦,抱歉。这就是我在Python课上的想法。他们没有提到命名约定:/我应该在我的示例中更改它吗?或者我可以暂时不使用它吗?
如果另一个程序正在运行,而不是Python本身
。。。我不明白你的意思。进程运行。python是一种语言。如果您想知道某个进程是否正在运行,而不是另一个进程,那么它必须意味着某个进程想知道它本身是否正在运行。这就像是问“我还活着吗?”如果你能问这个问题,你就是。我的意思是,我想知道Python进程是否正在运行。你能一次将处理的数据拆分吗?@shx2我想我的意思是我想知道Python进程是否正在运行?对不起,如果我的措辞不好@托马斯芬兹尔不,我不能。正在运行的代码是arcpy模块的一部分(
arcpy.Buffer\u analysis
)。它查看shapefile的每一行,并在其周围生成一个缓冲区。所有这些都发生在ArGIS内部(据我所知),我不能为了包含可以帮助我跟踪进度的标记而将其拆分。哇!谢谢这正是我一直在寻找的解决方案。但我有一个问题:我们是否需要在事后“结束”这条线索?(我之所以这样假设,是因为我们是用
t.start()
来“启动”它的)。我这样问是因为当我稍后在脚本中尝试运行另一个arcpy函数时,它现在给了我一个错误[请参阅我对上述问题的编辑],我想知道这是否是由于我们创建的线程仍然存在的事实。谢谢不,我们不需要结束线程。您可以将线程视为在两个完全不同的程序之间来回跳转的进程。当一个程序得出结论时,该进程将不会在该线程中花费更多的时间,因此它好像没有有效地在那里。通过使用while循环,我们可以有效地等待线程完成,另一种方法是t.join()。您的另一个错误与此无关,似乎其中一个arcpy函数只是根据该回溯引发了一个异常。噢!我懂了。问题是,只有在执行线程时,我才会收到错误消息。如果我正常运行它,它会工作,所以我猜一定有一些剩余内存干扰了其他功能。你认为我应该打开一个新问题来获得帮助吗?线程共享相同的内存。我会尝试在while循环之后添加t.join(),以确保函数在程序的其余部分继续之前完成。也看看你能不能查一下前男友