[英]Pipe text to stdin of running python process
假設我有一個名為service.py的python腳本在后台作為一種守護程序運行,我想通過將文本傳遞到其stdin中來提供一些信息:
> pgrep -f service.py
[pid of process]
> echo -e 'test\n' > /proc/[pid of process]/fd/0
我的python腳本應采用其stdin中的任何內容並將其分配給變量inp :
import sys
while True:
inp = sys.stdin.readline()
#do something with inp
但是當我做上面的事情時,它只是打印出stdin流:
> python service.py
test
如果我的腳本中只是字面上的意思,效果是一樣的
import sys
inp = sys.stdin.readline() #sys.stdin.readline() never returns
#script never exits
我究竟做錯了什么?
您可以將命名管道與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 )
關鍵是必須將stdin稱為管道或命名管道,這就是為什么您可以使用mkfifo
,另請參見如何從外部進程將數據寫入現有進程的STDIN? (python部分)以及如何從外部進程將數據寫入現有進程的STDIN? (操作系統部分)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.