ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4189

python sending argument to a running process

I have a flutter project called zed, my goal is to monitor the output of flutter run, as long as pressing r, the output will increase.

enter image description here

To automatically implement this workflow, my implementation is

import subprocess

bash_commands = f'''
cd ../zed
flutter run  --device-id web-server --web-hostname 192.168.191.6 --web-port 8352
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
output, err= process.communicate(bash_commands.encode('utf-8'))
print(output, err)
output, _ = process.communicate('r'.encode('utf-8'))
print(output)

It's not working as I expected, there is nothing printed on the screen.

Upvotes: 2

Views: 288

Answers (1)

SargeATM
SargeATM

Reputation: 2841

Use process.stdin.write() instead of process.communicate()

process.stdin.write(bash_commands)
process.stdin.flush()

But why you ask

Popen.communicate(input=None, timeout=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

communicate(...) doesn't return until the pipe is closed which typically happens when the subprocess closes. Great for ls -l not so good for long running subprocesses.

Upvotes: 2

Related Questions