python 管道 非阻塞_我可以在Linux上打开命名管道以使用Python进行非阻塞写入吗?...

I created a fifo file using mkfifo. Is it possible to open/write to this without blocking? I'd like to be agnostic whether there is a reader or not.

The following:

with open('fifo', 'wb', 0) as file:

file.write(b'howdy')

Just stalls at the open until I do a cat fifo from another shell. I want my program to make progress regardless there's a data consumer watching or not.

Is there a different linux mechanism I should be using perhaps?

解决方案

From man 7 fifo:

A process can open a FIFO in nonblocking mode. In this case, opening or read-only will succeed even if no-one has opened on the write side yet, opening for write-only will fail with ENXIO (no such device or address) unless the other end has already been opened.

So the first solution is opening FIFO with O_NONBLOCK. In this case you can check errno: if it is equal to ENXIO, then you can try opening FIFO later.

import errno

import posix

try:

posix.open('fifo', posix.O_WRONLY | posix.O_NONBLOCK)

except OSError as ex:

if ex.errno == errno.ENXIO:

pass # try later

The other possible way is opening FIFO with O_RDWR flag. It will not block in this case. Other process can open it with O_RDONLY without problem.

import posix

posix.open('fifo', posix.O_RDWR)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Python使用 `subprocess.Popen` 方法开启阻塞模式,你可以使用 `subprocess.PIPE` 参数来重定向子进程的标准输出和标准错误输出,并使用 `communicate` 方法来获取子进程的输出结果。 以下是一个示例: ```python import subprocess # 启动子进程并立即继续执行接下来的程序 process = subprocess.Popen(['command', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 阻塞模式下读取子进程的输出结果 output, error = process.communicate() # 处理子进程的输出结果 ``` 在上述示例中,我们将 `stdout` 和 `stderr` 参数都设置为 `subprocess.PIPE`,这样子进程的输出将会被重定向到管道中。然后,我们可以使用 `communicate` 方法来读取子进程的输出结果。注意,`communicate` 方法会等待子进程执行完毕并返回输出结果。 另外,如果你希望在启动子进程后立即继续执行接下来的程序而不等待子进程执行完毕,可以使用 `process.poll()` 方法来检查子进程是否已经执行完毕。如果返回值为 `None`,表示子进程还在运行;如果返回值不为 `None`,则表示子进程已经执行完毕。 以下是一个使用阻塞模式的示例: ```python import subprocess # 启动子进程并立即继续执行接下来的程序 process = subprocess.Popen(['command', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 检查子进程是否已经执行完毕 while process.poll() is None: # 这里可以继续执行其他操作 pass # 子进程已经执行完毕,可以处理子进程的输出结果 output, error = process.communicate() ``` 这样,你可以在子进程执行的同时,继续执行其他操作。当子进程执行完毕后,再使用 `communicate` 方法来获取输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值