【问题标题】:Pipe text to stdin of running python process将文本通过管道传输到正在运行的 python 进程的标准输入
【发布时间】:2023-03-23 21:21:01
【问题描述】:

假设我有一个名为 service.py 的 Python 脚本在后台作为一种守护进程运行,我想通过将文本输入其标准输入来为其提供一些信息:

> pgrep -f service.py
[pid of process]
> echo -e 'test\n' > /proc/[pid of process]/fd/0

我的 python 脚本应该采用其标准输入中的任何内容并将其分配到变量inp

import sys
while True: 
   inp = sys.stdin.readline()
   #do something with inp

但是当我执行上述操作时,它只是打印标准输入流:

> python service.py 
test            

如果我只是在我的脚本中使用它,效果是一样的

import sys
inp = sys.stdin.readline() #sys.stdin.readline() never returns
                           #script never exits

我做错了什么?

【问题讨论】:

  • 您是否尝试过调试您的代码以查看inp 是否真的被分配了某个值?问题可能出在 while 循环的代码中。
  • 不,sys.stdin.readline() 永远不会返回,我放置的所有内容都不会被执行。
  • @languitar 你说得对,非常感谢

标签: python stdin


【解决方案1】:

您可以将 命名管道mkfifo (https://serverfault.com/questions/443297/write-to-stdin-of-a-running-process-using-pipe) 一起使用

剩下的就是:

mkfifo yourfifo
cat > yourfifo &
mypid=$!
yourprogram < yourfifo

现在您可以使用

将数据发送到您的程序
`echo "Hello World" > yourfifo`

(https://askubuntu.com/questions/449132/why-use-a-named-pipe-instead-of-a-file)

关键是标准输入必须被称为 pipe命名管道 这就是为什么你可以使用mkfifo,另见How to write data to existing process's STDIN from external process?(python 部分)和How to write data to existing process's STDIN from external process?(操作系统部分)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-07-10
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多