如何以字符串形式执行python打印语句? [英] How to get execution of python print statements as a string?

查看:107
本文介绍了如何以字符串形式执行python打印语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python脚本,其中包含一个列表,该列表包含python打印语句作为字符串.在我的函数中,我正在使用for循环来运行exec函数来运行那些语句.

I am writing a python script which contains a list containing python print statements as a string. In my function, I am using a for loop to run exec function to run those statements.

这是我的功能:

g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]

def run_statements():
    for item in g_list:
        exec(item)

运行run_statements()函数时,得到以下输出:

When I run run_statements() function, I get the following output:

Wow! 
Great! 
Epic!

基本上,我想将输出保存为字符串,以便以后可以将其保存到数据库中.

Basically, I want to save the output as a string so that later, I can save it to my database.

有人知道我该怎么做吗?

Does anyone have any idea how can I do it?

编辑:在以下问题上:

At the following question: python: get the print output in an exec statement He is trying to get output, My question is different in a way that I am trying to get output as a string

推荐答案

如果您确实需要在字符串列表中使用print语句(与另一个答案中建议的具有类似名称的类打印函数相反) ),您可以在仔细,仔细,小心地保存旧的打印功能后,将名称print重新分配给自己的函数,以便您可以仔细,仔细,小心地将名称print恢复为正确的定义.像这样:

If you really need a print statement in the list of strings (as opposed to a print-like function with a different name, as suggested in another answer), you can reassign the name print to your own function, after carefully, carefully, carefully saving the old print function so you can carefully, carefully, carefully restore the name print to its proper definition. Like this:

>>> g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
>>> old_print = print
>>> def print(s): # redefining the built-in print function! terrible idea
...   global catstr
...   catstr += s
...
>>> catstr = ""
>>> for s in g_list: exec(s)
...
>>> catstr
'Wow!Great!Epic!'
>>> print = old_print # Don't forget this step!

这是完全不道德的,我不建议您这样做.我只是说你可以做到.

This is completely immoral, and I did not advise you to do it. I only said you can do it.

要强调该计划的不可取性:exec很少使用;有危险;很少应该将内置函数的名称重新分配给不同的函数;有危险.在相同的代码中执行这两个操作确实可能会毁了您的一天,尤其是在维护程序员稍微修改"您的代码而没有意识到潜在影响的情况下.

To stress the inadvisability of this plan: exec should be used rarely; it is dangerous; reassigning the names of built-in functions to different functions should be done very rarely; it is dangerous. Doing both in the same code could really ruin your day, especially after a maintenance programmer edits your code "just a little," without realizing the potential impact.

这篇关于如何以字符串形式执行python打印语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆