相关疑难解决方法(0)

如何在Python中打印到stderr?

有几种方法可以写入stderr:

# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"

sys.stderr.write("spam\n")

os.write(2, b"spam\n")

from __future__ import print_function
print("spam", file=sys.stderr)
Run Code Online (Sandbox Code Playgroud)

这似乎与Python#13 †的禅宗相矛盾,那么这里有什么区别,这种方式有哪些优点或缺点?应该使用哪种方式?

应该有一个 - 最好只有一个 - 显而易见的方法.

python printing stderr zen-of-python

1246
推荐指数
13
解决办法
77万
查看次数

python - 防止IOError:[Errno 5]在没有stdout的情况下运行时输入/输出错误

我有一个脚本通过cronjob在服务器上自动运行,它导入并运行其他几个脚本.

其中一些使用打印,这自然会创建,IOError: [Errno 5] Input/output error因为脚本运行时没有连接任何SSH /终端,因此没有正确的标准设置.

关于这个主题有很多问题,但我找不到任何实际解决它的人,假设我无法删除打印或更改执行的脚本.

我尝试了几件事,包括:

class StdOut(object):
    def __init__(self):
        pass
    def write(self, string):
        pass
sys.stdout = StdOut()
sys.stderr = StdOut()
Run Code Online (Sandbox Code Playgroud)

from __future__ import print_function
import __builtin__

def print(*args, **kwargs):
        pass
    __builtin__.print = print
Run Code Online (Sandbox Code Playgroud)

但它都不起作用.我认为它只会影响模块本身,而不会影响我以后导入/运行的模块.

那么如何创建一个会影响流程中所有模块的存根标准输出?就像我说的,我不想更改从主模块执行的脚本,但我可以更改导入模块中的所有内容.只是为了清除 - 一切都是进口的,没有新的流程产生等.

谢谢,

python stdout python-2.7

7
推荐指数
1
解决办法
7280
查看次数

标签 统计

python ×2

printing ×1

python-2.7 ×1

stderr ×1

stdout ×1

zen-of-python ×1