如何从Python中的函数exec()中提取文本
我想使用exec()函数在主脚本中执行子脚本。但是我想与其他字符串组合这样做,但是由于exec()命令是一个非类型,因此我无法在父脚本中加入子脚本的输出。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
exec
在大多数情况下应避免,因为它会导致难以理解和维护的代码。您真的可以因为没有使用更好的方法而无法使用它。如果您的其他脚本是Python脚本,则似乎您有要在多个位置重复使用的部分。然后,您不能将这些零件放在功能或类(及时)中,然后在您需要的地方导入它们?
另外,如果另一个问题是您要重复使用的代码是打印的,那么有一种方法可以解决此问题:让您的函数返回值,然后在最后在一个位置进行打印。显然,打印不会给您以后使用的值,它只是将其输出到控制台(或其他任何地方)。也就是说,它执行副作用。仅采用输入和返回值(因此不执行副作用)的函数称为纯净。这样纯粹的功能的好处是,您可以将它们粘合在一起(又称“构成”它们)。
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).