プログラムの標準入力および標準出力ロギング

プログラムの標準入力および標準出力ロギング

私が望むのは、プログラムを実行してstdinとstdoutを記録することですが、stdinがファイルから提供されることを望みます。

私はscript log.txt < input.txtそれがうまくいくと思いましたが、標準入力は記録されず、出力のみが記録されるため、動作しません。

input.txtはどこにありますか?

./program
something for the stdin of program
some more stuff

答え1

これが最善の解決策ではないかもしれませんが、次のことができます。

cat file.txt | tee -a stdin.txt | ./program | tee -a stdout.txt

どちらのティーでも同じファイルを使用できますが、入力と出力が破損して読み取れない可能性があります。

答え2

あなたはすでに標準入力ログを持っています:それはあなたのファイルです。

それ以外の場合(これが達成したいかどうかはわかりません)、stdinとstdoutの両方を含むログが必要な場合は、処理前にstdinからstdoutに行を読み取るようにプログラムを変更できます。

答え3

私は結局これを一つにまとめました。

import subprocess
import time
import sys

log = open(sys.argv[3], 'w')

input = open(sys.argv[2], 'r')

p = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

def readAllSoFar(proc, retVal=''):
  while (subprocess.select.select([proc.stdout],[],[],0)[0]!=[]):
    retVal+=proc.stdout.read(1)
  return retVal

while True:
    print('starting loop')
    line = input.readline()
    print('read line ' + line)
    if not line:
        print('breaking')
        break

    print('before sleep1')
    time.sleep(0.1)
    print('before readAllSoFar')
    output = readAllSoFar(p)
    print('got output' + output)
    log.write(output)
    time.sleep(0.1)
    log.write(line)
    p.stdin.write(line)

実行するpython runner.py ./program_to_run input.txt output.txt

コマンドのすべての出力が10分の1秒以内に完了すると仮定します。

関連情報