stderr.write;打印字符串

时间:2011-07-12 11:57:17

标签: python stderr

我是Python的新手,在使用stderr.write函数时遇到了一些麻烦。我将尝试用代码来说明它。在我这样做之前:

print "Unexpected error! File {0} could not be converted." .format(src)

但后来我想将错误消息与其他状态消息分开,所以我尝试这样做:

sys.stderr.write "Unexpected error! File %s could not be converted." src

但这会导致错误。我也搜索了它,但我找不到任何东西。有人可以帮帮我吗。如何使用src打印字符串stderr.write

4 个答案:

答案 0 :(得分:8)

在Python 2.x中:

sys.stderr.write("Unexpected error! File %s could not be converted." % src)

或者,在Python 2.x和3.x中:

sys.stderr.write("Unexpected error! File {0} could not be converted.".format(src))

答案 1 :(得分:1)

Python中的函数需要后跟parens((...)),可选地包含参数,以便被调用。

sys.stderr.write("Unexpected error! File %s could not be converted.\n" % (src,))

答案 2 :(得分:0)

sys.stderr.write是一个函数,所以要调用该函数,你需要在参数周围使用括号:

In [1]: src='foo'

In [2]: sys.stderr.write("Unexpected error! File %s could not be converted."%src)
Unexpected error! File foo could not be converted.

请注意,从Python3开始,print也是一个函数,也需要括号。

答案 3 :(得分:0)

你错过了(,)和%:

import sys
sys.stderr.write("Unexpected error! File %s could not be converted." % src)