Vinay Surve
Vinay Surve

Reputation: 85

How to identify a python statement in a string?

I am doing a project in python with the following requirement: I have a variable like:

some_variable = "os.getcwd()/local/bin"

Now there is a python statement "os.getcwd()" in the variable . I have to identify it , execute it and replace the value in the variable.

Note: Any python statement can occur in the string. I have to identify it, separate it and execute and replace the original variable with its value.

In the variable after execution if current working directory is

/home/xyz

then the variable should contain

/home/xyz/local/bin

Like os.getcwd(), any python statement can occur. How to identify the python statement in a string?

Upvotes: 1

Views: 208

Answers (1)

rainer
rainer

Reputation: 7099

As mentioned in the comments, this is generally very hard (for example, because you cannot decide whether an identifier is part of the text or a python name).

Therefore, I'd suggest changing your input a bit (assuming this is possible in your setting): Python template engines usually use some kind of escape sequence to denite the begin and end of a python statement. For mako, eg., you'd use the string some_variable = "${os.getcwd()}/local/bin", which makes the replacement easy. Additionally, adopting this syntax means that you can just use mako right away and don't have to implement anything yourself.

Of course there are a lot of alternatives to mako, it just was the first one to come to my mind.

Upvotes: 2

Related Questions