【发布时间】: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 你说得对,非常感谢