Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python 3.5中打印exec()函数的输出?_Python 3.x_Python 3.5 - Fatal编程技术网

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

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

我如何让您将python命令传递给exec()命令,等待完成,并打印出刚刚发生的所有事情的输出

很多代码都使用StringIO,这是Python 3.5中没有的。如果您真的想捕获所有输出,那么最好将命令写入脚本并使用执行它

下面是一个例子:

#!/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'
$