简体   繁体   中英

how to extract the text from the exec() of function in python

I want to use exec() function to execute a child script inside the main script. but I wanted to do so with other strings in combination but since the exec() command is a nonetype I'm unable to concatenate the output of the child script in the parent script.

exec is to be avoided most of the time because it leads to code that's difficult to understand and maintain. You really can get away with not using it as there are better approaches.

If your other script is a Python script, it seems like you have parts that you want to reuse in multiple places. Can't you then put those parts in functions, or classes (as appropriate) and then import them in the places you need them?

Also, if the other problem is that the code you want to reuse is printing then there's a way to remedy that: have your functions return values instead and do the printing all in one place at the end. Obviously printing doesn't give you the value to use later, it just outputs it to the console (or wherever else). That is, it performs a side effect. Functions that just take inputs and return values (and thus do not perform side effects) are called pure. The good thing about such pure functions is that you can glue them together (aka "compose" them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM