Using variables in signal handler - require global?

后端 未结 5 1860
不思量自难忘°
不思量自难忘° 2021-01-01 10:10

I have a signal handler to handle ctrl-c interrupt. If in the signal handler I want to read a variable set in my main script, is there an alternative to using a \"global\" s

5条回答
  •  悲&欢浪女
    2021-01-01 11:04

    You can access outer-scope variables from within an inline-defined function, like so:

    my_values = {'foo':'bar'}
    def handler(signum, frame):
        for key,val in my_values.items():
            print key,val
        my_values['bat']='baz'
        #remember to use mutable types, like dicts or lists
    
    signal.signal(signal.SIGINT, handler)
    

提交回复
热议问题