Hans Krupakar
Hans Krupakar

Reputation: 4261

Python background shell script communication

I have 2 python scripts, foo.py and bar.py. I am running foo.py in the background using

python foo.py &

Now I want to run bar.py and use the stdout from this file to trigger script inside foo.py. Is this possible? I'm using Ubuntu 16.04 LTS.

Upvotes: 2

Views: 1017

Answers (2)

dvorkanton
dvorkanton

Reputation: 36

You could use UNIX named pipe for that.

First, you create named pipe object by executing mkfifo named_pipe in the same directory, where you have your python files.

Your foo.py then could look like this:

while True:
    for line in open('named_pipe'):
        print 'Got: [' + line.rstrip('\n') + ']'

And your bar.py could look like this:

import sys

print >>open('named_pipe', 'wt'), sys.argv[-1]

So, you run your consumer process like this: python foo.py &. And finally, each time you execute python bar.py Hello, you will see the message Got: [Hello] in your console.

UPD: unlike Paul's answer, if you use named pipe, you don't have to start one of the processes from inside the other.

Upvotes: 2

Paul92
Paul92

Reputation: 9062

There is a system that actually comes from UNIX world that creates pipes between processes. A pipe is basically a pair of file descriptors, each program having access to one of them. One program writes to the pipe, while the other reads:

https://docs.python.org/2/library/subprocess.html

However, this requires an aditional script where you start foo and bar as subprocesses and connect their outputs/inputs.

Upvotes: 0

Related Questions