python - prevent IOError: [Errno 5] Input/output error when running without stdout

自闭症网瘾萝莉.ら 提交于 2019-12-01 04:04:52

Modifying the builtin or changing sys.stdout should work (except for subprocesses—but you ruled those out) as long as you do it early enough. If not, though, there's a lower level trick that's much easier:

  • run your python scripts with I/O redirection that discards output:

    python foo.py >/dev/null 2>&1
    

    (assuming Unix-y scripts, as implied by "cron" in the question)

  • or, redirect file descriptors 1 and 2 (same idea as above, but done within your Python startup rather than as part of the cron-invoked command):

    import os
    fd = os.open(os.devnull, os.O_RDWR)
    # NB: even if stdin is closed, fd >= 0
    os.dup2(fd, 1)
    os.dup2(fd, 2)
    if fd > 2:
        os.close(fd)
    

    (this particular bit of code has the side effect of making /dev/null act as stdin, if all descriptors were closed). [Edit: I started with with open(...) and then switched to os.open and did not test the final version. Fixed now.]

All that said, a good cron really should have stdout and stderr connected somewhere, and should email the output/error-output to you. Not all cron versions are this nice though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!