【问题标题】:How do I print the output of the exec() function in python 3.5?如何在 python 3.5 中打印 exec() 函数的输出?
【发布时间】:2016-10-13 08:58:09
【问题描述】:

我怎样才能让你将 python 命令传递给 exec() 命令,等待完成,然后打印出刚刚发生的所有事情的输出?

那里的许多代码都使用 StringIO,这是 Python 3.5 中不包含的东西。

【问题讨论】:

标签: python-3.x python-3.5


【解决方案1】:

你不能。 Exec just executes in place and returns nothing。如果您真的想捕获所有输出,最好的办法是将命令写入脚本并使用subprocess 执行它。

这里有一个例子:

#!/usr/bin/env python3

from sys import argv, executable
from tempfile import NamedTemporaryFile
from subprocess import check_output

with NamedTemporaryFile(mode='w') as file:
    file.write('\n'.join(argv[1:]))
    file.write('\n')
    file.flush()

    output = check_output([executable, file.name])

    print('output from command: {}'.format(output))

并运行它:

$ ./catchandrun.py 'print("hello world!")' 
output from command: b'hello world!\n'
$

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2021-12-29
    • 2010-09-18
    相关资源
    最近更新 更多