在python I中,分别使用称为os.close的0、1和2,它们是标准输入、输出和误差。我如何重新打开/重新初始化它们?这样,我将在函数或代码块开始时关闭它们,并在返回之前重新打开它们。
PS:对于python的具体细节和泛型细节都将不胜感激。
发布于 2013-04-28 15:26:44
您不能关闭它们,然后重新打开它们,但是一旦完成,您可以复制它们并恢复以前的值。像这样的东西;
copy_of_stdin = os.dup(0) // Duplicate stdin to a new descriptor
copy_of_stdout = os.dup(1) // Duplicate stdout to a new descriptor
copy_of_stderr = os.dup(2) // Duplicate stderr to a new descriptor
os.closerange(0,2) // Close stdin/out/err
...redirect stdin/out/err at will...
os.dup2(copy_of_stdin, 0) // Restore stdin
os.dup2(copy_of_stdout, 1) // Restore stdout
os.dup2(copy_of_stderr, 2) // Restore stderr
os.close(copy_of_stdin) // Close the copies
os.close(copy_of_stdout)
os.close(copy_of_stderr)https://stackoverflow.com/questions/16264317
复制相似问题