簡體   English   中英

如何使用自定義類文件對象作為子進程 stdout/stderr?

[英]How to use a custom file-like object as subprocess stdout/stderr?

考慮這段代碼,其中產生了一個subprocess.Popen 我想寫入子進程的stdoutstderr以轉到我的自定義文件對象的.write()方法,但情況並非如此。

import subprocess

class Printer:

    def __init__(self):
        pass

    def write(self, chunk):
        print('Writing:', chunk)

    def fileno(self):
        return 0

    def close(self):
        return

proc = subprocess.Popen(['bash', '-c', 'echo Testing'], 
                        stdout=Printer(),
                        stderr=subprocess.STDOUT)
proc.wait()

為什么不使用.write()方法,在這種情況下指定stdout=參數有什么用?

根據文檔

stdin、stdout 和 stderr 分別指定了執行程序的標准輸入、標准輸出和標准錯誤文件句柄。 有效值為PIPE、DEVNULL、現有文件描述符(正整數)、現有文件對象和 None

使用subprocess.PIPE

proc = subprocess.Popen(['bash', '-c', 'echo Testing'], 
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)
print('Writing:', proc.stdout.read())
# OR  print('Writing:', proc.stdout.read().decode())

不直接。 也許未來的 Python 版本將支持將類文件對象轉換為某種自動填充管道,但關鍵是子進程需要訪問它可以讀取的文件句柄,而無需以某種方式調用 Python 代碼。 這意味着它需要在操作系統級別工作,這意味着它僅限於幾種可能性:

  • 從父進程繼承 stdin(當stdin=None時發生)
  • 從文件中獲取輸入(當stdin是文件或整數文件句柄時會發生這種情況)
  • 從管道獲取輸入(在stdin=subprocess.PIPE時發生)

使用類文件對象意味着您將不得不自己讀取數據,然后通過管道將其輸入。

例如:

proc = subprocess.Popen(['sha256sum', '-'], stdin=subprocess.PIPE)
while True:
    chunk = filelike.read(BLOCK_SIZE)
    proc.stdin.write(chunk)
    if len(chunk) < BLOCK_SIZE:
        break
proc.wait()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM