Python-变量范围和修改
我正在编写一个Python脚本,它主要是一个GUI框架,用于在Windows主机上进行实时取证数据收集。到目前为止,我还没有遇到过很多无法解决的问题。但这件事让我很难堪。这可能是一个涉及不正确变量范围的问题,但就我个人而言,我找不到这个问题。脚本本身超过两千行,所以除非另有指示,否则我将复制相关部分 我在代码中的某个地方做了更改,这破坏了功能。它过去工作得很好,现在我不明白为什么不能。这肯定会让我在将来的项目中使用版本控制软件 奇怪的是根本没有抛出异常 我要做的是让用户选择Tkinter Checkbutton小部件,它对应于他们想要执行的可选功能。我已经为每个Checkbutton小部件设置了Tkinter IntVars,并将这些IntVars放入一个数组中以便于枚举。GUI有一个“开始”按钮,按下该按钮时,启动Start()函数。如果IntVar设置为1(表示选择),此函数应枚举数组中的Checkbutton IntVar并执行相关函数 我的代码的所有其他部分都按预期运行。我在填充数组时感觉很糟糕。似乎我无法修改数组,即使在函数中声明为全局数组。如果我手动设置数组中的值,它将按预期运行。我无法遍历IntVars并将“全局”数组设置为其正确值。这两个数组似乎从未被修改过,就好像没有一个Checkbutton IntVars被选中时被设置为“1”Python-变量范围和修改,python,python-2.7,scope,Python,Python 2.7,Scope,我正在编写一个Python脚本,它主要是一个GUI框架,用于在Windows主机上进行实时取证数据收集。到目前为止,我还没有遇到过很多无法解决的问题。但这件事让我很难堪。这可能是一个涉及不正确变量范围的问题,但就我个人而言,我找不到这个问题。脚本本身超过两千行,所以除非另有指示,否则我将复制相关部分 我在代码中的某个地方做了更改,这破坏了功能。它过去工作得很好,现在我不明白为什么不能。这肯定会让我在将来的项目中使用版本控制软件 奇怪的是根本没有抛出异常 我要做的是让用户选择Tkinter Che
#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()
要尝试简化流程,请执行以下操作:
这是一篇很长的帖子。。。第一次在这里发帖,所以我为巨大的文字墙提前道歉。我不想从我的任何代码中获利,所以如果您希望看到完整的预期功能,我可以分享我的代码库。我可以向感兴趣的人提供整套服务。提前谢谢 尝试向
doOptionalCollection()
函数添加一个全局选项项。对于optionfunctions
也是一样。同样,我看到optionArray
在start()
中没有声明global
,因此您也应该在那里为它添加一个global
语句。尽管根据项目的使用方式,并不总是需要将其声明为全局,但无论如何,这样做是一个好主意,尤其是当您遇到与之相关的问题时。除此之外,这是一个很好的内部文档。有趣的是,我尝试在上面所有访问/修改OptionalItem、FileType和optionArray的函数的开头为这些数组添加global
声明。这就是我被困的地方——不管是全球还是全球,它们都没有被修改。我找不到可信的解释来解释原因。再加上。。。我只是试着做了你描述的修改。optionalitems[]和filetypes[]仍然没有得到修改。我可以进一步建议的是继续抛出代码,并将内容缩减到最小的数量,这仍然显示问题,并在此处更新您的问题。理想情况下,如果你能把它归结为我们可以独立执行的东西,那将是理想的。