0

Aplogies if I have the terminology all wrong; I am still learning the basics of Python. I have been unable to google this issue, probably in large part because I don't know the terminology..

So. I have built a class within a .py script with LOTS of methods/functions. To keep this remotely simple, I want to call these from a commandline argument. I have no idea how to explain it, and I can't find anhy examples, so I will try to demo it:

Take for example mute_on as the function that I want to call. I run the script with the function/method in the argument, like:

python3 ./myscript.py mute_on

I assume we'd import sys(?), define the class and the function, and create the relevant object from the class:

import sys

class TelnetAVR(PioneerDevice):

    def mute_on(self, mute):
        self.telnet_command("MO")

mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10) 

...and lastly I would like the commandline argument to call the method/function - instead of calling it explicitly like:

mypioneer.mute_volume()

..I want to use the arg (sys.argv[1]) to dynamically call the function, like:

mypioneer.{sys.argv[1]}()

Any ideas, kind people? I have been auto-referred to What is getattr() exactly and how do I use it? but I have no idea how that information can help me here.

I have tried setting cmnd = 'turn_off' and then the following failed...;

getattr(mypioneer, str(cmnd))
getattr(mypioneer, cmnd) 

Thanks!

  • 1
    Possible duplicate of [What is getattr() exactly and how do I use it?](https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it) – awesoon Jun 30 '18 at 06:51

1 Answers1

0

This answer seems a little basic, but I cannot complain as to its efficacy;

mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10)     
exp = 'mypioneer.' + sys.argv[1] + '()'
print('Executing: ' + exp  )
exec(exp)

I gave up loking for a graceful answer, and simply constructed a string that I wanted to execute (exp) based on the commandline argument. Works great.. Home Assistant can use the same script to call 50 telnet controls over my Pioneer AVR.