Python:在一个函数中调用另一个函数的变量,但不使用全局变量
我写了下面的代码,目的是检查三个文件,看看哪些文件存在。如果文件存在,就对这些文件进行“扫描”;如果某个文件不存在,也没关系,只要对存在的文件进行“扫描”,然后生成相应的输出文件。
我正在处理的程序包含以下代码:
def InputScanAnswer():
scan_number = raw_input("Enter Scan Type number: ")
return scan_number
这个函数用来检查这三个文件是否存在,如果存在,就给 hashcolumn
和 filepathNum
赋特定的值。
def chkifexists():
list = ['file1.csv', 'file2.csv', 'file3.csv']
for filename in list:
if os.path.isfile(filename):
if filename == "file1.csv":
hashcolumn = 7
filepathNum = 5
if filename == "file2.csv":
hashcolumn = 15
filepathNum = 5
if filename == "file3.csv":
hashcolumn = 1
filepathNum = 0
#print filename, hashcolumn, filepathNum
def ScanChoice(scan_number):
if scan_number == "1":
chkifexists()
onlinescan(filename, filename + "_Online_Scan_Results.csv", hashcolumn, filepathNum) #this is what is giving me errors...
elif scan_number == "2":
print "this is scan #2"
elif scan_number =="3":
print "this is scan #3"
else:
print "Oops! Invalid selection. Please try again."
def onlinescan(FileToScan, ResultsFile, hashcolumn, filepathNum):
# web scraping stuff is done in this function
我遇到的错误是 global name 'filename' is not defined
。我意识到问题出在我试图把 chkifexists()
函数里的局部变量传给 onlinescan()
的参数。我尝试在
return filename
return hashcolumn
return filepathNum
chkifexists()
函数的末尾使用这个方法,但也没有成功。有没有办法在
onlinescan(filename, filename + "_Online_Scan_Results.csv", hashcolumn, filepathNum)
这一行中不使用全局变量呢?我知道全局变量不太推荐使用,我希望能用其他方法解决这个问题。另外,onlinescan()
中的 hashcolumn
和 filepathNum
参数和这个问题有关系吗?
1 个回答
4
在 chkifexists
这个函数里,你可以这样返回所有三个变量:
return (filename, hashcolumn, filepathNum)
你可以通过这样调用这个函数来获取这些变量:
(filename, hashcolumn, filepathNum) = chkifexists()
现在你在函数内部就可以使用这些变量,而不需要用到全局变量了!
其实,你也不一定需要括号。说实话,我也不太明白我为什么要加上它们。不过无论有没有括号,效果都是一样的,所以随便吧。