Python后台shell脚本通信

Python background shell script communication

我有 2 个 python 脚本,foo.pybar.py。我正在 运行ning foo.py 在后台使用

python foo.py &

现在我想 运行 bar.py 并使用此文件中的标准输出来触发 foo.py 中的脚本。这可能吗?我正在使用 Ubuntu 16.04 LTS。

有一个实际上来自 UNIX 世界的系统在进程之间创建 pipes。管道基本上是一对文件描述符,每个程序都可以访问其中一个。一个程序写入管道,而另一个读取:

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

但是,这需要一个额外的脚本,您可以在其中将 foo 和 bar 作为子进程启动并连接它们 outputs/inputs。

你可以使用 UNIX named pipe

首先,您通过在您拥有 python 文件的同一目录中执行 mkfifo named_pipe 来创建命名管道对象。

您的 foo.py 可能如下所示:

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

你的 bar.py 可能看起来像这样:

import sys

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

所以,您 运行 您的消费者过程是这样的:python foo.py &。 最后,每次执行 python bar.py Hello 时,您都会在控制台中看到消息 Got: [Hello]

UPD:与 Paul 的回答不同,如果您使用 named 管道,则不必从另一个进程中启动其中一个进程。