Get function from string containing full name

I have a line like:

str = "pwd.getpwuid(1000)"

Now, if I try eval (), that may throw an exception, because I have not imported pwd yet (or maybe not if I have).

So, I decided to write a parser that: breaks this line into "." and get the list:

lis = ["pwd", "getpwuid(1000)"]

then take lis[0]if it does not contain "("or ")", I call

importlib.import_module(lis[0])

and then again eval.

Can I do the same better?

+4
source share
2 answers

Found a solution:

I have to change the lines containing the function body:

str = "(lambda x: __import__('pwd').getpwuid(x))(1000)"

eval () on this is ok!

(lambda or def are obviously the same)

0
source

lis [2] args lis [3]

lib = importlib.import_module(lis[0])
lib.__dict__[lis[1]](*list[2],**list[3])
0

Source: https://habr.com/ru/post/1534834/


All Articles