python - 如何解决 'Global name self is not defined'?

标签 python ironpython

这个简单的代码正在监听 C::上的更改

import clr
clr.AddReference('System.IO')
from System.IO import (DriveInfo)
from WatchDir import WatchedItem
from MobileNotifier import MobileNotifier

class WinWash(object):
    ''' Watches the server for important changes. '''
    def __init__(self, notifier):
        self.notifier = notifier
        self.min_size = 20000

    def on_low_space(self, sender, event):
        ''' Notifies if free space is below min_size '''
        my_drives = DriveInfo.GetDrives()
        for drive in my_drives:
            megabytes_free = (drive.AvailableFreeSpace / 1000000)

            if megabytes_free < self.min_size:
                self.notify('Disk.Space-{0}-{1}.MB'.format(drive.Name, megabytes_free))
                print 'Sent!'

    def notify(event, message):
        ''' Send message to user. '''
        app = 'WinWash'
        self.notifier(app, event, message)

def main():
    notifier = MobileNotifier()
    win = WinWash(notifier)
    disk = WatchedItem('C:\\')
    # callback/event handler
    disk.watch_create(win.on_low_space)

    choice = ''
    while choice != 'q':
        choice = raw_input("Press 'q' to exit: \n")

这里我使用 Windows CLR 来“轻松”监控文件系统。当引发事件(在本例中为文件创建)时,应调用回调方法:

import clr, os, re
clr.AddReference('System.IO')
from System.IO import (FileSystemWatcher, NotifyFilters)
from ConfigParser import SafeConfigParser
from MobileNotifier import MobileNotifier

class WatchedItem(object):
    """A watched item."""

    def __init__(self, dir):
        self.dir = dir
        self.matches = None
        self.subdirs = None
        self.watcher = None

    def __repr__(self):
        return '(matches: {num}) - {dir}'.format(dir=self.dir, num=len(self.matches.split(',')))

    def _create_watcher(self):
        ''' Returns a Watcher watching self.dir. '''
        watcher = FileSystemWatcher(self.dir)
        watcher.IncludeSubdirectories = self.subdirs
        watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
        return watcher

    def watch_create(self, callback):
        ''' Starts watching self.dir. Calls callback when an Event is raised. '''
        watcher = self._create_watcher()
        watcher.Created += callback
        watcher.EnableRaisingEvents = True
        self.watcher = watcher
        print 'Watching for creation:', self.dir

我猜回调有问题,因为当引发事件时我收到此错误(文件在 C: 上创建):

Unhandled Exception: IronPython.Runtime.UnboundNameException: global name 'self' is not defined
   at IronPython.Compiler.PythonGlobal.GetCachedValue(Boolean lightThrow)
   at IronPython.Compiler.PythonGlobal.get_CurrentValue()
   at IronPython.Compiler.PythonGlobalInstruction.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
   at IronPython.Compiler.PythonCallTargets.OriginalCallTarget2(PythonFunction function, Object arg0
, Object arg1)
   at IronPython.Runtime.FunctionCaller`2.Call2(CallSite site, CodeContext context, Object func, T0
arg0, T1 arg1)
   at IronPython.Runtime.Method.MethodBinding`1.SelfTarget(CallSite site, CodeContext context, Objec
t target, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg
1, T2 arg2)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`6.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2,
T3 arg3)
   at IronPython.Compiler.Ast.CallExpression.Invoke1Instruction.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2,
T3 arg3)
   at IronPython.Compiler.PythonCallTargets.OriginalCallTarget3(PythonFunction function, Object arg0
, Object arg1, Object arg2)
   at IronPython.Runtime.FunctionCaller`3.Call3(CallSite site, CodeContext context, Object func, T0
arg0, T1 arg1, T2 arg2)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0,
T1 arg1, T2 arg2, T3 arg3, T4 arg4)
   at CallSite.Target(Closure , CallSite , Object , Object , FileSystemEventArgs )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg
1, T2 arg2)
   at _Scripting_(Object[] , Object , FileSystemEventArgs )
   at System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e)
   at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
   at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeO
verlapped* overlappedPointer)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 nu
mBytes, NativeOverlapped* pOVERLAP)
Press any key to continue . . .

我对此感到困惑,我不确定如何避免 self,而且我也不确定哪个 self 导致了问题。

最佳答案

您没有在 WinWash 类中的方法通知声明中包含 self:

def notify(event, message):
    ''' Send message to user. '''
    app = 'WinWash'
    self.notifier(app, event, message)

应该是:

def notify(self, event, message):
    ''' Send message to user. '''
    app = 'WinWash'
    self.notifier(app, event, message)

关于python - 如何解决 'Global name self is not defined'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29925259/

相关文章:

python - 创建独立的可执行iron python 文件

python - 将 list.map 应用于 python 中的两个并行列表

当从 python 调用时,c# 需要额外的参数(.net 和 ironpython)

python - 在 pythonnet 中使用 OWdotNET.dll(.NET 的 python)

c# - 如何使用 IronPython 中的包调用 Python 脚本?

python - 使用 Pytest 和 Mock 测试查询数据库的 View

python - pylab : Bounding box despite frameon=False

python - 如何修复错误 "' id' : Select a valid choice"on Modelformset validation?

python - 如何加速 Pandas 操作(按嵌套列表项分组)

python - `heroku pgbackups:capture` 在服务器上运行什么命令来执行备份?