我想知道是否可以将我的 Python 执行结果保存为字符串。我尝试过Eval,Exec和Compile,但这些都不是我想要的结果。
我想要的是下面。
for i in range(10):
print("Hello World! " + str(i))
例如,我这里有这种代码。这种表达的结果是显而易见的。
Hello World! 0
Hello World! 1
...
Hello World! 8
Hello World! 9
我想将整个结果存储为字符串中。比如hello_world_string
. 我知道将第一个代码部分保存为文件,然后通过子进程或类似的函数方法使用 Python 执行它确实返回字符串类型作为其返回值。但是,我想知道是否有任何方法可以在不写入另一个文件的情况下执行此操作。
我是StackOverflow的新手。所以我可能犯了一些错误。 如果是这样,请告诉我。我很乐意尽快修改它们。
编辑:
对不起,我在这个问题上犯了一些错误。我认为代码不是我想做的的正确例子。
例如
a = [10, 20, 30, 40]
a.push
我们在示例中有一些错误。 此代码的重用将是
AttributeError: 'list' object has no attribute 'push'
我想将此输出保存为字符串。
这个问题似乎具有误导性。我对此深感抱歉。
更具体地说,Python 解释器或 Jupyter 笔记本"打印"代码如何运行和每个进程的输出。我想将这些"打印出来"数据捕获为字符串,而不考虑代码本身。
再次,我为让大家感到困惑而深感抱歉。 谢谢。
使用简单的捕获
exception_string = ""
try:
a = [10, 20, 30, 40]
a.push
except Exception as e:
exception_string = e
print (exception_string)
# 'list' object has no attribute 'push'
你应该使用subprocess
模块。它将终端输出存储在列表中。例如:
>>> import subprocess
# enter the command. For example I used "echo arg1 arg2" You can type your .py file directory...
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print (output)
arg1 arg2
希望它有帮助😊...
我不确定我是否理解您的问题,但您可以简单地将结果添加到初始字符串中,并仅调用一次打印方法:
hello_world_string=''
for i in range(10):
hello_world_string += "Hello World! " + str(i) + "n"
print(hello_world_string)
这是解决方案:
hello_world_string=''
对于范围 (10( 中的 i: hello_world_string += "Hello World!" + str(i( + "" 打印(hello_world_string(
输出:
Hello World! 0
Hello World! 1
Hello World! 2
Hello World! 3
Hello World! 4
Hello World! 5
Hello World! 6
Hello World! 7
Hello World! 8
Hello World! 9