What is StringIO in python used for in reality?

2019-03-07 17:56发布

I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one should/will use it? Thanks in advance

p.s. not to be confused with this question on stackoverflow: StringIO Usage which compares string and StringIo.

7条回答
走好不送
2楼-- · 2019-03-07 18:49

Django has a function call_command which is used to call management commands. This function prints output to stdout and doesn't return any value. If you want to know whether the command ran successfully or not, you have to look into output and decide.

Using StringIO, you can capture output and check if it is desired output or not.

with io.StringIO() as output:
    call_command('custom_command', stdout=output)
    if 'Success' not in output.getvalue():
        print('Custom command failed...')
查看更多
登录 后发表回答