开发者

Embedding executable python script in python string

开发者 https://www.devze.com 2023-04-04 08:09 出处:网络
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,

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 als开发者_运维知识库o 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.)


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

Some good links here and here


See the built-in eval() function.


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: {}

0

精彩评论

暂无评论...
验证码 换一张
取 消