简体   繁体   中英

Can a text file be updated by two programs simultaneously (live communication)?

I have a program that has c/c# abilities, and I have python. I want that program to update a text file, almost in milliseconds, and have the python to read that text file in milliseconds as well. How can I go achieve this?

Is it possible for a text file to be updated live by another program and be read live by python? Is there any alternative way to do this instead of relying on text file. Basically what I want to do is a bunch of computations on live data from that program using python and send back those computations to the program in form of commands.Can a file not be closed and reopened and yet updated in the memory?

If you start the C/C# process from python with subprocess.Popen then your two programs can communicate via the stdin and stdout pipes:

c_program = subprocess.Popen(["ARGS","HERE"],
                             stdin = subprocess.PIPE,  # PIPE is actually just -1
                             stdout= subprocess.PIPE,  # it indicates to create a new pipe
                             stderr= subprocess.PIPE  #not necessary but useful
                             )

Then you can read the output of the process with:

data = c_program.stdout.read(n) #read n bytes
#or read until newine
line = c_program.stdout.readline()

Note that both of these are blocking methods, although non blocking alternatives exist.

Also note that in python 3 these will return bytes objects, you can convert into a str with the .decode() method.

Then to send input to the process you can simply write to the stdin:

c_program.stdin.write(DATA)

Like the read above, in python 3 this method expects a bytes object. You can use the str.encode method to encode it before writing it to the pipe.


I have extremely limited knowledge of C# but from limited research it seems that you can read data from System.Console.In and write data to System.Console.Out , although if you have written programs in C# that run in a terminal, the same methods used to write data to the screen and read input from the user will work here too. (you can imagine the .stdout as the terminal screen and data python writes to .stdin the user input)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM