Python - Let a user input a function - python-3.x

I´m currently writing a test script for a custom python console. My question is, how do I let the user input a already defined function?
Example: My script gets an input from the user. It detects, that its a line of code, therefore executes it.
Does anyone know how I can implement this as code?
Thanks in advance!

If the functions are already defined I would suggest you define a dictionary of choices to pick from.
It's typically a very bad idea to let a user input and execute arbitrary code.

U can use the eval() function which is builtin. it takes the string parameter and executes the parsed string. For example:
x = 1
print(eval('x + 1'))
>>>2

Related

Using a commandline argument to call a class method

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!
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.

How do I call a Python function when another function has been called?

I am writing a Python python program that includes two functions: bot.say() and message_sent(). I want message_sent() to be called every time bot.say() is called, in an efficient manner. How would this be achieved?
One simple way would be make a function call both of them, and use that in your code instead of bot.say(). From the two examples you provided, assuming there's nothing else to pass in, you could do something like below.
def bot_message(bot):
bot.say()
message_sent()

Executing functions stored in a string

Lets say that there is a function in my Delphi app:
MsgBox
and there is a string which has MsgBox in it.
I know what most of you are going to say is that its possible, but I think it is possible because I opened the compiled exe(compiled using delphi XE2) using a Resource Editor, and that resource editor was built for Delphi. In that, I could see most of the code I wrote, as I wrote it. So since the variables names, function names etc aren't changed during compile, there should a way to execute the functions from a string, but how? Any help will be appreciated.
EDIT:
What I want to do is to create a simple interpreter/scripting engine. And this is how its supposed to work:
There are two files, scr.txt and arg.txt
scr.txt contains:
msg_show
0
arg.txt contains:
"Message"
And now let me explain what that 0 is:
First, scr.txt's first line is function name
second line tells that at which line its arguments are in the arg.txt, i.e 0 tells that "Message" is the argument for msg_show.
I hope my question is now clear.
I want to make a simple scripting engine.
In order to execute arbitrary code stored as text, you need a compiler or an interpreter. Either you need to write one yourself, or embed one that already exists. Realistically, the latter option is your best option. There are a number available but in my view it's hard to look past dwscript.
I think I've already solved my problem! The answer is in this question's first answer.
EDIT:
But with that, as for a workaround of the problem mentioned in first comment, I have a very easy solution.
You don't need to pass all the arguments/parameters to it. Just take my example:
You have two files, as mentioned in the question. Now you need to execute the files. It is as simple as that:
read the first line of scr.txt
check if it's a function. If not, skip the line
If yes, read the next line which tells the index where it's arguments are in arg.txt
pass on the index(an integer) to the "Call" function.
Now to the function which has to be executed, it should know how many arguments it needs. i.e 2
Lets say that the function is "Sum(a,b : integer)".It needs 2 arguments
Now let the function read the two arguments from arg.txt.
And its done!
I hope it will help you all.
And I can get some rep :)

List to String to List Python 3

I need to convert a list into a string and then do the reverse process. Note that one script will convert List->String and another script will convert String->List, so store the list in a variable is not a solution. Use split(', ') or similar is not a solution either in all cases. So, as a challange I invite you to do the conversion in the following example:
l = ['ab,.cd\'ac"', b'\x80', '\r\nHi, !', b'\x01']
str_l = str(l)
I have tried one thing that worked: using exec() built-in function but people says is not a good practice, so I invite you to give me another alternative. Also I am having problems using exec() inside a function but that's another question that you can check -> Using exec() inside a function Python 3
This should work:
str_l = ("|").join(l)
Which gives you your first string. Then do:
l_2 = str_l.split("|")
Which gives you your second list.

Same for loop, giving out two different results using .write()

this is my first time asking a question so let me know if I am doing something wrong (post wise)
I am trying to create a function that writes into a .txt but i seem to get two very different results between calling it from within a module, and writing the same loop in the shell directly. The code is as follows:
def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
#opens a file with certain naming convention
n = 0
for word in para2:
if word == para1:
file.write(para2[n-1]+'\n')
print(para2[n-1]) #intentionally included as part of debugging
n+=1
function("targetstr". targettext)
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable
when I define this function in the shell, I get the correct words appearing. However, when i call this same function through a module(in the shell), nothing appears in the shell, and the text file shows a bunch of numbers (eg: 's93161), and no new lines.
I have even gone to the extent of including a print statement right after declaration of the function in the module, and commented everything but the print statement, and yet nothing appears in the shell when I call it. However, the numbers still appear in the text file.
I am guessing that there is a problem with how I have defined the parameters or how i cam inputting the parameters when I call the function.
As a reference, here is the desired output:
‘She
Ashley
there
Kitty
Coates
‘Let
let
that
PS: Sorry if this is not very clear as I have very limited knowledge on speaking python
I have found the solution to issue. Turns out that I need to close the shell and restart everything before the compiler recognizes the changes made to the function in the module. Thanks to those who took a look at the issue, and those who tried to help.

Resources