我已经编写了一个API,用户可以将sql查询的输出指向:
1> Excel(ExcelOut类)
2> CSV(CSVOut类)
3>标准输出(StdOut类)
对于前两种输出types,我希望用户提供一个文件位置,然后API检查该位置是否存在参数validation
对于标准输出,我想知道是否有任何validation需要? 即在任何情况下, API的用户(开发人员)都不知道代码运行时sys.stdout不“可用” ?
stdout不可写的原因有很多。 这里有些例子:
# 1. Run with stdout explicitly closed: $ ./yourscript >&- # 2. Run in the background and then closing the terminal $ ./yourscript & exit # 3. No space on the device (/dev/full simulates this for testing): $ ./yourscript > /dev/full # 4. Run with a pipe that closes immediately: $ ./yourscript | true # 5. Run with a pipe that closes after the first 10 lines: $ ./yourscript | head -n 10
在写入时,每个错误都被封装在Python ErError中,Errno被设置为:
EBADF (Bad file descriptor)
EIO (Input/output error)
ENOSPC (No space left on device)
EPIPE (Broken pipe)
前几个写入调用将成功,然后如#4中的EPIPE
(换句话说,一次工作并不意味着总是工作)。
在开始写入之前,试图确定stdout是否有效是很有用的(基本检查可以通过例如os.fstat
来完成)。 大多数程序应该假定它是可用的,并且优雅地处理错误。