Python 3.x 如何在python 3.5中打印exec()函数的输出?
我如何让您将python命令传递给exec()命令,等待完成,并打印出刚刚发生的所有事情的输出 很多代码都使用StringIO,这是Python 3.5中没有的。如果您真的想捕获所有输出,那么最好将命令写入脚本并使用执行它 下面是一个例子:Python 3.x 如何在python 3.5中打印exec()函数的输出?,python-3.x,python-3.5,Python 3.x,Python 3.5,我如何让您将python命令传递给exec()命令,等待完成,并打印出刚刚发生的所有事情的输出 很多代码都使用StringIO,这是Python 3.5中没有的。如果您真的想捕获所有输出,那么最好将命令写入脚本并使用执行它 下面是一个例子: #!/usr/bin/env python3 from sys import argv, executable from tempfile import NamedTemporaryFile from subprocess import check_out
#!/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'
$