AloPancho
AloPancho

Reputation: 3

send string between python script

I want to send 'hello world' to a script in python already running in ubuntu.

The script that's always running is this one (part of it):

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

it throws the pid of the running process so I can send stuff by console with:

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

It will print it in the console! but I can't send \x15 or EOF or anything to break sys.stdin.readline() and do some other stuff in my script, for example:

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

Does anyone know how to do it? The script that send the string will not always be running, but the script that receives the info will be always running.

PROBLEM SOLVED!

Thank's to Rafael this is the solution:

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

Sender:

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

path = "/tmp/my_program.fifo"


fifo = open(path, "w")

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

Upvotes: 0

Views: 755

Answers (2)

Rafael Lerm
Rafael Lerm

Reputation: 1400

Since you obviously don't have a problem with being limited to a Unix system, you can use named pipes to communicate with the program. Very unix-y way to work.

Python provides the os.mkfifo function to ease creating named pipes; otherwise they work just like files.

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16711

Write to a text file that is read by the already running program. The two can interact via this file. For example, these two programs simultaneously read and write to an initially empty text file.

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)

Upvotes: 1

Related Questions