【问题标题】:Python: significance of -u option?Python:-u 选项的意义?
【发布时间】:2012-12-24 20:59:18
【问题描述】:

我注意到在一些 python 代码中 -u 用于启动 python 解释器。 我查看了 python 的手册页,但我无法从中得到太多。请给我一些例子。

【问题讨论】:

标签: python


【解决方案1】:

来自python --help:

-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'

手册页指出:

-u     Force  stdin,  stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin,
       stdout and stderr in binary mode.  Note that there is internal buffering  in  xreadlines(),  readlines()
       and  file-object  iterators  ("for  line in sys.stdin") which is not influenced by this option.  To work
       around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

Python 以缓冲模式打开 stdin、-out 和 -error 流;它将读取或写入更大的块,将数据保存在内存中,直到达到阈值。 -u 禁用这些缓冲区。

此外,python 可以解释打开文件上的换行符,并将它们与本机平台换行符(文本模式)相互转换。 -u 选项禁用此转换,允许您处理二进制数据而不必担心\r\n 组合可能会发生什么。相当于使用open()函数打开文件时使用rb或wb模式。

【讨论】:

  • 无缓冲二进制标准输出和标准错误; ??
  • 对于 Python3.4,stdin 总是被缓冲,不管 '-u' 的使用。 (来自python3.4 --help)
  • @JonathanHartley:这里的联机帮助页很可能不正确;请注意--help 信息(我想说来自 Python 2.7)也没有提到标准输入。这是因为标准输入缓冲超出了 Python 的控制范围。
  • @JonathanHartley:Python 3 联机帮助页也取消了 stdin。请参阅Turn off buffering in pipe 了解使标准输入无缓冲的方法。
【解决方案2】:

Python 针对读取和打印大量数据进行了优化。其中一项优化是 Python 解释器的标准输入和输出为buffered。这意味着每当程序尝试使用其中一个流时,解释器会将使用阻塞成大块,然后一次性发送所有块。这比单独发送每个单独的读/写要快,但显然存在数据可能会在中间“阻塞”的缺点。

-u 标志关闭此行为。

【讨论】:

    【解决方案3】:

    我也遇到了这个问题,发现这样做 :

    sudo systemctl enable myservice.service

    已解决问题 - 我已检查此线程中列出的所有其他内容。只需要这样做一次,服务就会在每次后续启动时启动。我的也是一个python脚本

    【讨论】:

      猜你喜欢
      • 2014-01-11
      • 2012-09-08
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多