Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active April 4, 2018 09:31
Show Gist options
  • Save devlights/45b63296fe4e9e4e5352dda52639579a to your computer and use it in GitHub Desktop.
Save devlights/45b63296fe4e9e4e5352dda52639579a to your computer and use it in GitHub Desktop.
[python] subprocess.popen で ファイルディスクリプタを渡して別プロセス側でも同じファイルを同一 fd で読み取るサンプル (pass_fds)
"""
起動引数で指定された fd (ファイルディスクリプタ) を使ってデータを読み取り表示します。
(注意) subprocess.popen経由で呼び出されることを想定しています。
"""
import itertools
import os
import sys
def go():
fd = int(sys.argv[1])
with os.fdopen(fd, mode='r', encoding='utf-8') as f:
for l in itertools.islice(f, 7):
print(l)
if __name__ == '__main__':
go()
"""
subprocess.popen()の呼び出しでファイルディスクリプタを渡して処理するサンプルです。
(注意) pass_fdsパラメータはWindowsでは対応していない。
REFERENCES::
https://tokibito.hatenablog.com/entry/2016/10/23/042920
https://docs.python.jp/3/library/subprocess.html#subprocess.Popen
"""
import itertools
import pathlib
import subprocess
import sys
def go():
p = pathlib.Path(__file__)
f = p.open(mode='r', encoding='utf-8')
fd = f.fileno()
with f:
for l in itertools.islice(f, 7):
print(l)
proc = subprocess.Popen(
[sys.executable, "fd_cat.py", str(fd)],
pass_fds=[fd])
proc.wait()
if __name__ == '__main__':
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment