在 python 脚本之间发送字符串

send string between python script

我想将 'hello world' 发送到 python 中的脚本,已经 运行 在 ubuntu 中。

总是运行的脚本是这个(部分):

print("$ echo 'foobar' > {0}".format(get_ttyname()))
print("$ echo 'foobar' > /proc/{0}/fd/0".format(os.getpid()))
sys.stdin.readline()

它会抛出 运行 进程的 pid,这样我就可以通过控制台发送内容:

echo 'hello script!' > /proc/PID/fd/0

它会打印在控制台!但我不能发送 \x15 或 EOF 或任何东西来破坏 sys.stdin.readline() 并在我的脚本中做一些其他的事情,例如:

def f(e):
    print 'we already read:',s

while True:
    s = sys.stdin.readline()
    print 'we break the readline'
    f(s)    
    .....blablabla some other stuff, and then we return to the top of the while to keep reading...

有人知道怎么做吗?发送字符串的脚本不会总是 运行,但接收信息的脚本总是 运行.

问题已解决!

感谢拉斐尔,这就是解决方案:

Reader:

import os
import sys


path = "/tmp/my_program.fifo"
try:
         os.mkfifo(path)
except OSError:
         pass

fifo = open(path, "r")

while True:
         for line in fifo:
                  linea = line
                  print "Received: " + linea,
         fifo.close()
         if linea =='quit':
                  break
         fifo = open(path, "r")

发件人:

# -*- coding: utf-8 -*-
import os

path = "/tmp/my_program.fifo"


fifo = open(path, "w")

fifo.write("Hello Wordl!!\n")
fifo.close()

写入已被 运行 程序读取的文本文件。两者可以通过这个文件进行交互。例如,这两个程序同时读取和写入一个最初为空的文本文件。

already.py

# executed 1st

import time

while True:
    text = open('file.txt').read()
    print 'File contents: ' + text
    time.sleep(5)

program.py

# executed 2nd

import time

while True:
    text = open('file.txt', 'a')
    text.write(raw_input('Enter data: '))
    text.close()
    time.sleep(5)

既然你显然没有被限制在Unix系统上的问题,你可以使用命名管道与程序通信。非常 unix-y 的工作方式。

Python 提供了 os.mkfifo 函数来简化命名管道的创建;否则它们就像文件一样工作。