getattr and method name

Chris Rebert clp2 at rebertia.com
Sun Oct 2 18:34:44 EDT 2011


On Sun, Oct 2, 2011 at 3:02 PM, Kevin Walzer <kw at codebykevin.com> wrote:
> I'm seeing a very odd error in an application I'm developing using Python
> 2.7.2, on Mac OS 10.7.
>
> This application uses a wrapper method to look up other method names via
> getattr and then call those methods. I have not previously had an issue with
> this name, but for some reason this functionality no longer works as
> expected.
>
> Here is the relevant code:
>
>    #run command with root privileges
>    def runCommand(self, cmd, *args):
>        try:
>            functionstring = args[2]
>            callfunction = getattr(self, functionstring.split('.')[1])
>            self.passtext = self.tk.call('authorize::getAuthPassword')
>            callfunction()
>        except:
>            try:
>                print cmd
>                functionstring = cmd.split()[2]
>                callfunction = getattr(self, functionstring.split('.')[1])
>                self.passtext = self.tk.call('authorize::getAuthPassword')
>                callfunction()
>            except:
>                raise
>
> I use this approach to call the method named in the "cmd" parameter because
> I also have to look up a password name that is returned by an underlying Tk
> package that I use in my application (that's the reason for the
> 'self.tk.call'). What is happening is when I use the "callfunction()" call,
> instead of the method name being called, a string like this is being
> invoked:
>
> <bound method phynchronicityApp.scanPackages of <__main__.phynchronicityApp
> instance at 0x101b232d8>>

Er, your terminology seems kinda funky. Do you mean to say that
repr(callfunction) results in that string (which is normal and
expected), or that the return value from callfunction() is that string
(which would be rather bizarre)? I would presume the former. [One does
not call/invoke a string; strings aren't callable.]

> The "scanPackages" method (just to use it as an example) uses Popen to call
> an underlying system tool on the OS. However, when invoked via
> callfunction(), the 'bound method...' string is passed to the OS instead as
> a command! As a result, I get this output from the pipe:
>
> /bin/sh: bound: No such file or directory

Either you've elided some important part of the code from your
fragment above, or the problem would seem to lie in scanPackages()
[presumably its Popen() call is screwy]. Please post the code for
scanPackages(), and (if applicable) the full code for runCommand().

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list