【发布时间】:2016-10-13 08:58:09
【问题描述】:
我怎样才能让你将 python 命令传递给 exec() 命令,等待完成,然后打印出刚刚发生的所有事情的输出?
那里的许多代码都使用 StringIO,这是 Python 3.5 中不包含的东西。
【问题讨论】:
标签: python-3.x python-3.5
我怎样才能让你将 python 命令传递给 exec() 命令,等待完成,然后打印出刚刚发生的所有事情的输出?
那里的许多代码都使用 StringIO,这是 Python 3.5 中不包含的东西。
【问题讨论】:
标签: python-3.x 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'
$
【讨论】: