gpt4 book ai didi

c# - 两个程序可以同时更新文本文件(实时通信)吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:30:28 24 4
gpt4 key购买 nike

我有一个具有 c/c# 功能的程序,并且我有 python。我希望该程序几乎以毫秒为单位更新文本文件,并让 python 也以毫秒为单位读取该文本文件。我怎样才能做到这一点?

文本文件是否可以由另一个程序实时更新并由 python 实时读取?有没有其他方法可以代替依赖文本文件来执行此操作。基本上我想做的是使用 python 对来自该程序的实时数据进行一堆计算,并将这些计算以命令的形式发送回该程序。文件不能关闭并重新打开并在内存中更新吗?

最佳答案

如果您使用 subprocess.Popen 从 python 启动 C/C# 进程,那么您的两个程序可以通过 stdinstdout 管道进行通信:

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
)

然后你可以读取这个过程的输出:

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

请注意,尽管 non blocking alternatives 这两种方法都是阻塞方法存在。

另请注意,在 python 3 中,这些将返回 bytes 对象,您可以使用 .decode() 方法将其转换为 str

然后要将输入发送到进程,您只需写入标准输入即可:

c_program.stdin.write(DATA)

与上面的read 一样,在python 3 中,此方法需要一个bytes 对象。在将其写入管道之前,您可以使用 str.encode 方法对其进行编码。


我对 C# 的了解非常有限,但从有限的研究来看,您似乎可以 read data from System.Console.Inwrite data to System.Console.Out ,尽管如果您用 C# 编写了在终端中运行的程序,那么用于将数据写入屏幕和读取用户输入的相同方法在这里也适用。 (您可以将 .stdout 想象成终端屏幕和数据 python 写入 .stdin 用户输入)

关于c# - 两个程序可以同时更新文本文件(实时通信)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com