Wirawan Purwanto
Wirawan Purwanto

Reputation: 4043

Embedding executable python script in python string

If you are a bash/posix sh wizard you will know the $(command substition) feature in bash, which could even be inserted in a string. For example,

$ echo "I can count: $(seq 1 10 | tr -d '\n')" 
I can count: 12345678910

You can imagine all wild things to do with this, especially to make a dynamically formed string. No need to do if..else block outside the string; just embed the code inside! I am s spoiled by this feature. So here's the question: in python, can we do something similar? Is there one person already devising a module to accomplish this task?

(Just a side comment: admittedly having this kind of feature is powerful but also opening yourself to a security risk. The program can be vulnerable to code injection. So think thoroughly before doing this especially with a foreign string coming from outside the code.)

Upvotes: 1

Views: 956

Answers (3)

Shaurya Chhabra
Shaurya Chhabra

Reputation: 72

Are you looking for an fstring: Instead of starting the string with ' We start the string with f' And whenever we want to embed any script we just put inside these: {}

Upvotes: 0

Alex Smith
Alex Smith

Reputation: 1535

See the built-in eval() function.

Upvotes: 0

hymloth
hymloth

Reputation: 7035

You can use eval() and all of it's potential risks...

Some good links here and here

Upvotes: 1

Related Questions