读取/写入同一文件的两个进程Python [英] Two processes reading/writing to the same file Python

查看:421
本文介绍了读取/写入同一文件的两个进程Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个进程正在读取文件(使用file.read()),还有一个进程正在写入同一文件(file.write()).问题是它不起作用-我没有收到任何错误,但它们不能同时运行.我尝试使读取和写入操作无阻塞,然后刷新流,如下所示:

I have one process who's reading from a file (using file.read()) and one process who's writing to the same file (file.write()). The problem is it doesn't work - I get no errors but they can't operate at the same time. I've tried making the read and write operations none-blocking and then flushing the stream, as follows:

fcntl.fcntl(file, fcntl.F_SETFL, os.O_NONBLOCK)
file.write(msg)
file.flush()

我完全误会了吗?一个人应该如何完成从不同过程对一个文件的写入和读取?

Am I completely misunderstanding it? How should one accomplish writing and reading to one file from different processes?

推荐答案

test1.py

import os
f = open('txt.txt', 'a', os.O_NONBLOCK)
while 1:
        f.write('asd')
        f.flush()

test2.py

import os
f = open('txt.txt', 'r', os.O_NONBLOCK)
while 1:
    print f.read(3)

这对我来说很好.

这篇关于读取/写入同一文件的两个进程Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆