在python脚本之间发送字符串

时间:2015-01-20 20:59:14

标签: python linux

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

始终运行的脚本就是这个(部分):

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...

有谁知道怎么做?发送字符串的脚本并不总是在运行,但接收信息的脚本将始终在运行。

问题解决了!

感谢Rafael这是解决方案:

阅读器:

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()

2 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:1)

由于您显然不会受限于Unix系统,因此可以使用命名管道与程序进行通信。非常unix-y的工作方式。

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