Python变量范围和修改

2024-10-02 18:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本,它主要是一个GUI框架,用于在Windows主机上实时收集取证数据。到目前为止,我还没有遇到过很多无法解决的问题。但这一次让我难堪。这可能是一个涉及不适当变量范围的问题,但在我的一生中,我找不到这个问题。脚本本身超过两千行,因此除非另有指示,否则我将复制相关部分。在

我在代码的某个地方做了一个改动,破坏了我的功能。以前它可以完美地按预期工作,现在我不知道为什么不能。这肯定会导致我在将来的项目中使用版本控制软件,这是肯定的。在

奇怪的是,根本没有抛出异常。在

我要做的是让用户选择对应于他们想要执行的可选功能的Tkinter Checkbutton小部件。我为每个Checkbutton小部件设置了Tkinter IntVars,并将这些IntVars放入数组中以便于枚举。GUI有一个“Start”按钮,当按下该按钮时,启动Start()函数。此函数应枚举数组中的Checkbutton IntVars,并在IntVar设置为1(表示选择)时执行相关函数。在

我代码的所有其他部分都按预期运行。我在填充数组的时候过得很糟糕。似乎我不能修改数组,即使在函数中声明为全局的。如果我手动设置数组中的值,它将按预期工作。我不能遍历IntVars并将“global”数组设置为正确的值。这两个数组似乎从来没有被修改过,就好像没有一个Checkbutton IntVars通过被选中而设置为“1”。在

#this is an array of integers corresponding to the checked
#state of desired filetypes for collection
filetypes = [0]*34

#this is an array of integers corresponding to optional collection items
optionalitems = [0]*10

#... snipped ...

#This function performs just fine if the filetypes array is set manually...
#extensions[] is an array containing file extension strings corresponding
# to the Checkbuttons on the fileSelector Toplevel widget.
#outputdirs[] is an array containing strings with a desired output directory.
def collectFiles():
    global filetypes

    n = 0
    print("Parsing checkboxes for file collection...\r\n")
    for item in filetypes:
        if item:
           print(extensions[n] + " selected...")
           #make output dir corresponding to the desired extension
           outputdest = cwd + "/output/" + computername + outputdirs[n]
           if not os.path.exists(outputdest):
               print(outputdest + " does not exist, creating...")
               os.makedirs(outputdest)
               print("Collection for " + outputdirs[n] + " beginning...")
               for drive in drives:
                   print("Searching drive " + drive + "...")
                   for filename in search(drive, extensions[n]):
                       try:
                           i = 2
                           #outpath = cwd + "/output/" + username + outputdirs[n]
                           tempbasename = os.path.basename(filename)
                           testpath = os.path.join(outputdest, tempbasename)
                           tempbasename2 = ""
                           while os.path.exists(testpath):
                               print(testpath + " exists in output directory.")
                               tempbasename2 = str(i) + "_" + tempbasename
                               i += 1
                               testpath = os.path.join(outputdest, tempbasename2)
                           shutil.copy2(filename,testpath)
                           print("Copied:\n\t" + filename + "\n to:\n\t" + testpath + "\n")
                           logfile.write(str(datetime.datetime.now()) + "- Copied:\r\n\t" + filename
                                     + "\r\n to:\r\n\t" + testpath + "\r\n\r\n")
                       except:
                           print("****Problem copying: " + filename + "\n")
                           logfile.write(str(datetime.datetime.now()) + "****Problem copying: " + filename
                                     + "\r\n\r\n")
                           pass
        n += 1

#... snipped ...

#here's where the oddness begins.
#The optionalitems array SHOULD be set outside of this
# function, before it is called.
def doOptionalCollection():
    x = 0
    for item in optionalitems:
        if item:
            optionfunctions[x]()
        x = x + 1

    collectFiles()

#this is the routine called when the "Start" button is pressed.
# The goal here is to enumerate the checkboxes on the GUI, and
# fill filetypes[] and optionalitems[] with values corresponding to
# whether or not the Checkbuttons are selected.
def start():
    global filetypes
    global optionalitems

    #... snipped ...
    #code here performs baseline forensic data collection,
    # and performs exactly as intended.
    #... snipped ...

    #get status of checkboxes and update optionalitems array.
    # optionArray is the Array of IntVars associated with Tkinter Checkbuttons
    # obj.get() --> 0 = unchecked, 1 = checked
    i = 0
    for obj in optionArray:
        optionalitems[i] = obj.get()
        i = i + 1

    doOptionalCollection()

#this is for a dialog-style window that pops up when a button is pressed.
# The dialog contains 34 checkboxes, each with a variable to hold the state.
def showFileSelector():
    global filetypes
    fs = Toplevel(master=root)
    fs.title("Collect files by extension...")
    #set up a grid based on the extensions dictionary keys.
    # have the grid wrap on the 6th element.

    #... snipped, setup of Checkbutton tkinter windgets ...

    buttonArray = [txtButton, pdfButton, logButton, docButton, docxButton,
               rarButton, zipButton, isoButton, jarButton, jpgButton,
               jpegButton, bmpButton, pngButton, gifButton, exeButton,
               pptButton, pptxButton, aviButton, mp4Button, movButton,
               flvButton, mpgButton, wmvButton, mp3Button, flacButton,
               wmaButton, m4aButton, wavButton, psdButton, rawButton,
               apkButton, szipButton, indexdatButton, thumbsdbButton]

    #using filetypes array, set the status of the checkbox.
    #this is helpful if the dialog is re-opened, it will
    # re-populate the dialog with previous selections.
    x = 0
    for item in buttonArray:
        if filetypes[x]:
            item.select()
        x = x + 1

    varArray = [txtvar, pdfvar, logvar, docvar, docxvar,
            rarvar, zipvar, isovar, jarvar, jpgvar,
            jpegvar, bmpvar, pngvar, gifvar, exevar,
            pptvar, pptxvar, avivar, mp4var, movvar,
            flvvar, mpgvar, wmvvar, mp3var, flacvar,
            wmavar, m4avar, wavvar, psdvar, rawvar,
            apkvar, szipvar, indexdatvar, thumbsdbvar]

    def accept():
        global filetypes
        #user has possibly chosen files to collect by extension.
        # iterate varArray to determine what files to collect,
        # and store the result in filetypes[].
        #This assignment also does not work.
        x = 0
        for var in varArray:
            #var.get() to get the values of checkboxes
            # 0 = unchecked
            # 1 = checked
            filetypes[x] = var.get()
            x = x + 1
        fs.destroy()


    def cancel():
        #user has decided to discard selections and close
        # the window.
        fs.destroy()

    #... snipped, GUI placement ...

#back to the base-level indentation (no indents... not inside any functions)

#... snipped, optional item GUI Checkbutton setup ....

optionArray = [productkeyvar, outlookvar,
               recyclebinvar, skypevar,
               prefetchvar, installlogvar,
               allmediavar, win7jumplistvar,
               win7thumbcachevar, recentfilesvar]

optionfunctions = [collectProductKeys, collectOutlookAttachments,
                   collectRecycleBin, collectSkypeHistory,
                   collectPrefetchFolder, collectDeviceInstallationLogs,
                   collectMediaFiles, collectWin7JumpList,
                   collectWin7ThumbnailCache, collectShortcutRecentFiles]

#... snipped, more GUI setup ...

#and then, the obligatory...
root.mainloop()

为了简化流程:

  1. 用户可以在GUI上设置选项,也可以选择要收集的文件类型。如果用户选择了要收集的任何文件类型,则应该已经使用所需的选择填充filetypes[]。似乎没有修改此数组。

  2. 用户按开始按钮,开始按钮命令是Start()函数。定义了全局变量—即filetypes[]和optionItems[]。

  3. 在start()内部,基线鉴证收集发生,并按预期运行。

  4. 仍然在start()中,获取可选集合的复选框的状态,并填充optionItems[]。似乎没有修改此数组。

  5. start()然后调用doOptionalCollection()。

  6. doOptionalCollection()还定义了全局变量-filetypes[]和optionItems[]。当数组被枚举时,它们被读取为它们的初始值-全部为零。这意味着没有执行任何所需的收集函数。

  7. doOptionalCollection()调用collectFiles()。

  8. collectFiles()有一个全局定义-这主要是我在函数内部解析filetypes[]时的一个工件。由于filetypes数组始终为零,因此除非在代码中手动设置,否则不会收集任何内容。

这是一个很长的帖子。。。第一次在这里发帖,所以我提前为巨大的文字墙道歉。我不想从我的任何代码中获利,所以如果你想看到完整的预期功能,我可以分享我的代码库。我可以把整个包裹提供给感兴趣的人。提前谢谢!在


Tags: oftheto函数inforisgui