-1
如何获得它,以便您将python命令传递给exec()命令,等待完成并打印出刚刚发生的所有事情的输出?如何在python 3.5中打印exec()函数的输出?
其中的许多代码都使用StringIO,这是Python 3.5中没有包含的。
如何获得它,以便您将python命令传递给exec()命令,等待完成并打印出刚刚发生的所有事情的输出?如何在python 3.5中打印exec()函数的输出?
其中的许多代码都使用StringIO,这是Python 3.5中没有包含的。
你不能。 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'
$
[包括在Python 3.5 StringIO的(https://docs.python.org/3.5/library/ io.html#io.StringIO) – Taywee