如何在python 3.5中打印exec()函数的输出?

时间:2016-06-13 03:11:33

标签: python-3.x python-3.5

如何将python命令传递给exec()命令,等待完成,并打印刚刚发生的所有内容的输出?

许多代码都使用StringIO,这是Python 3.5中没有包含的内容。

1 个答案:

答案 0 :(得分:0)

你做不到。 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'
$