albertyw/albertyw.com

View on GitHub
app/notes/20180323-0805.md

Summary

Maintainability
Test Coverage
Example of Python Subprocess

python-subprocess

1521792347

I needed to test out a thing with the subprocessing module and wrote an
example of using it to run multiple processes in parallel, then reading
all the stdouts and stderrs at the end:

`process.sh`:

```python
import subprocess
import time


commands = ['./time.sh'] * 5
outputs = [None] * len(commands)
processes = [None] * len(commands)


start = time.time()


for i, command in enumerate(commands):
    process = subprocess.Popen([command], stdout=subprocess.PIPE)
        processes[i] = process


for i, process in enumerate(processes):
    outputs[i] = process.communicate()
        print(i, outputs[i])


print('elapsed seconds: ', time.time() - start)
```

`time.sh`:

```bash
#!/bin/bash
sleep 2
date
```