python中的dup、dup2、tmpfile和stdout

2024-06-12 00:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是here的后续问题。


我想去的地方

我希望能够暂时将stdout重定向到临时文件,而python仍然能够打印到stdout。这将涉及以下步骤:

  1. 创建stdout的副本(new
  2. 创建临时文件(tmp
  3. 将stdout重定向到tmp
  4. 告诉python使用new作为stdout
  5. tmp重定向到“真正的”标准输出
  6. 告诉python再次使用“real”标准输出
  7. 阅读并关闭tmp

实施

我试图通过以下方式实现上述目标:

import os
import subprocess
import sys

#A function that calls an external process to print to stdout as well as
#a python print to pythons stdout.
def Func(s, p = False):
    subprocess.call('echo "{0}"'.format(s), shell = True)
    if p:
        print "print"

sil = list() # <-- Some list to store the content of the temp files

print "0.1" # Some testing of the
Func("0.2") # functionality

new = os.dup(1)    # Create a copy of stdout (new)
tmp = os.tmpfile() # Create a temp file (tmp)

os.dup2(tmp.fileno(), 1)            # Redirect stdout into tmp
sys.stdout = os.fdopen(new, 'w', 0) # Tell python to use new as stdout

Func("0.3", True) # <--- This should print "0.3" to the temp file and "print" to stdout

os.dup2(new, 1)                   # Redirect tmp into "real" stdout
sys.stdout = os.fdopen(1, 'w', 0) # Tell python to use "real" stdout again

# Read and close tmp
tmp.flush()
tmp.seek(0, os.SEEK_SET)
sil.append(tmp.read())
tmp.close()

我想在此稍作总结。
到这里为止,控制台的输出应该是:

0.1
0.2
print

sil应该是这样的:['0.3\n']。所以到现在为止,一切都在运转。但是,如果我再次像这样重做上面的脚本:

print "1.1" # Some testing of the
Func("1.2") # functionality

new = os.dup(1)    # Create a copy of stdout (new)
tmp = os.tmpfile() # Create a temp file (tmp)

os.dup2(tmp.fileno(), 1)            # Redirect stdout into tmp
sys.stdout = os.fdopen(new, 'w', 0) # Tell python to use new as stdout

# This should print "0.3" to the temp file and "print" to stdout and is the crucial point!
Func("1.3", True) 

os.dup2(new, 1)                   # Redirect tmp into "real" stdout
sys.stdout = os.fdopen(1, 'w', 0) # Tell python to use "real" stdout again

# Read and close tmp
tmp.flush()
tmp.seek(0, os.SEEK_SET)
sil.append(tmp.read())

出现错误,输出如下:

1.1
1.2
/bin/sh: line 0: echo: write error: Bad file descriptor
print

sil读取:['0.3\n', '']

换句话说:第二个Func("1.3", True)无法写入临时文件。

问题

  1. 首先,我想知道为什么我的脚本不能像我希望的那样工作。意思是,为什么只有在脚本的前半部分才能写入临时文件?
  2. 我对dupdup2的用法还是有点困惑。虽然我想我了解将stdout重定向到临时文件的工作原理,但我现在完全知道为什么os.dup2(new, 1)在做它正在做的事情。也许答案可以详细说明我的脚本中所有的dupdup2都在做什么^ ^

Tags: ofthetonewosstdoutsysreal
1条回答
网友
1楼 · 发布于 2024-06-12 00:52:11

得到“坏文件描述符”的原因是垃圾收集器为您关闭stdout FD。考虑这两条线:

sys.stdout = os.fdopen(1, 'w', 0)    # from first part of your script
...
sys.stdout = os.fdopen(new, 'w', 0)  # from second part of your script

现在,当这两个文件对象中的第二个被执行时,第一个文件对象的引用计数将降为零,垃圾收集器将其销毁。文件对象在被销毁时关闭其关联的fd,而fd恰好是1=stdout。因此,在销毁使用os.fdopen创建的对象时需要非常小心。

这里有一个小例子来说明这个问题。os.fstat只是用作一个示例函数,当您向它传递一个关闭的fd时,它会触发“坏文件描述符”错误。

import os
whatever = os.fdopen(1, 'w', 0)
os.fstat(1)
del whatever
os.fstat(1)

实际上,我正好有一个上下文管理器,我认为它确实(或者至少,在我的情况下,我需要一个命名的tempfile)满足您的需要。您可以看到它重用了原来的sys.stdout对象,以避免close出现问题。

import sys
import tempfile
import os

class captured_stdout:
    def __init__(self):
        self.prevfd = None
        self.prev = None

    def __enter__(self):
        F = tempfile.NamedTemporaryFile()
        self.prevfd = os.dup(sys.stdout.fileno())
        os.dup2(F.fileno(), sys.stdout.fileno())
        self.prev = sys.stdout
        sys.stdout = os.fdopen(self.prevfd, "w")
        return F

    def __exit__(self, exc_type, exc_value, traceback):
        os.dup2(self.prevfd, self.prev.fileno())
        sys.stdout = self.prev

## 
## Example usage
##

## here is a hack to print directly to stdout
import ctypes
libc=ctypes.LibraryLoader(ctypes.CDLL).LoadLibrary("libc.so.6")
def directfdprint(s):
    libc.write(1, s, len(s))


print("I'm printing from python before capture")
directfdprint("I'm printing from libc before captrue\n")

with captured_stdout() as E:
    print("I'm printing from python in capture")
    directfdprint("I'm printing from libc in capture\n")

print("I'm printing from python after capture")
directfdprint("I'm printing from libc after captrue\n")

print("Capture contains: " + repr(file(E.name).read()))

相关问题 更多 >