Context
I am experimenting with a script that is similar to vegeta
's ramp-requests.py. In this script, I am running multiple subprocesses sequentially using subprocess.run()
, and expect the standard input of the script to be redirected to those subprocesses during their entire lifetime (5s each).
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
import time
rates = [1.0, 2.0, 3.0, 4.0]
# Run vegeta attack
for rate in rates:
filename='results_%i.bin' % (1000*rate)
if not os.path.exists(filename):
cmd = 'vegeta attack -format=json -lazy --duration 5s -rate %i/1000s -output %s' % (1000*rate, filename)
print(cmd, file=sys.stderr)
subprocess.run(cmd, shell=True, encoding='utf-8')
I invoke the script as follows, by piping an infinite amount of inputs to it, each input separated by a new line. vegeta
reads this input continuously until --duration
has elapsed:
$ target-generator | ./ramp-requests.py
Problem
The first subprocess (rate=1.0) seems to receive stdin as I expect, and the command runs successfully, every time.
The second iteration (rate=2.0), however, fails silently, along with all subsequent iterations. If I inspect the corresponding report files (e.g. results_2000.bin
) using the vegeta report
command, I see fragments of errors such as parse error: syntax error near offset 0 of 'ource":["c...'
.
My intuition is telling me that the second subprocess started consuming the input where the first one left it, in the middle of a line, but injecting a sys.stdin.readline()
after subprocess.run()
doesn't solve it. If that is the case, how can I cleanly solve this issue and ensure each subprocess starts reading from a "good" position?