全局文件变量无法访问外部函数(Python)

时间:2015-06-04 00:45:52

标签: python file io global-variables

当按下按钮时,变量日志会打开带有时间戳的文件,并且当按钮关闭时应该关闭。 但是,我无法关闭在另一个函数中打开的文件,即使该文件已被声明为全局。我试过把"全局文件"在两个功能之外,但这不起作用。

 if button_status==True: #Press start
    if First_run==True: #Start a new logfile
        global log
        log=open(Fname,'a')
        log.writelines(header)
        First_run=False

     #Other code here

if button_status==False:#press stop
    log.close()
    First_run=True

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试将global log之类的内容放在文件顶部附近,以便在任何方法或类之外声明它。然后摆脱LinkedList<String> servers = new LinkedList<String>(); .... String firstServerName = servers.removeFirst(); 行,它应该随处可见。

答案 1 :(得分:0)

当您在函数外部引用变量时,需要

global

log = False
if button_status==True: #Press start
if First_run==True: #Start a new logfile
    global log
    log=open(Fname,'a')
    log.writelines(header)
    First_run=False

 #Other code here

if button_status==False:#press stop
    global log
    log.close()
    First_run=True
相关问题