将run()的绑定/管道输出打开/插入到python3(lynux)函数中 [英] Binding / piping output of run() on/into function in python3 (lynux)
问题描述
我正在尝试使用通过 run 函数运行的外部程序的输出.
该程序定期抛出一行数据,我需要在我的脚本中使用
我找到了一个 subprocess 库,并使用了它的run()
/check_output()
示例:
def usual_process():
# some code here
for i in subprocess.check_output(['foo','$$']):
some_function(i)
I am trying to use output of external program run using the run function.
this program regularly throws a row of data which i need to use in mine script
I have found a subprocess library and used its run()
/check_output()
Example:
def usual_process():
# some code here
for i in subprocess.check_output(['foo','$$']):
some_function(i)
现在假设foo已经在PATH变量中,并且它会在半随机周期内输出一个字符串.
我希望程序做自己的事情,并且每次foo将新行发送到其输出时都运行some_function(i)
.
Now assuming that foo is already in a PATH variable and it outputs a string in semi-random periods.
I want the program to do its own things, and run some_function(i)
every time foo sends new row to its output.
有两个问题.将输出传递到for循环中并将其作为后台子进程运行 谢谢
which boiles to two problems. piping the output into a for loop and running this as a background subprocess Thank you
Update: I have managed to get the foo output onto some_function using This
with os.popen('foo') as foos_output:
for line in foos_output:
some_function(line)
根据此 os.popen 是不推荐使用的,但是我还没有弄清楚如何在python中传递内部进程 现在只需要弄清楚如何在后台运行此功能
According to this os.popen is to be deprecated, but I am yet to figure out how to pipe internal processes in python Now just need to figure out how to run this function in a background
推荐答案
SO,我已经解决了.
第一步是启动外部脚本:
proc=Popen('./cisla.sh', stdout=PIPE, bufsize=1)
SO, I have solved it.
First step was to start the external script:
proc=Popen('./cisla.sh', stdout=PIPE, bufsize=1)
接下来,我启动了一个函数,该函数将读取它并将其传递给管道
Next I have started a function that would read it and passed it a pipe
def foo(proc, **args):
for i in proc.stdout:
'''Do all I want to do with each'''
foo(proc).start()`
限制是:
如果您不希望捕获脚本错误,则必须将其插入.
其次是如果您杀死父母会留下僵尸,所以不要忘记在信号处理中杀死孩子
Limitations are:
If your wish t catch scripts error you would have to pipe it in.
second is that it leaves a zombie if you kill parrent SO dont forget to kill child in signal-handling
这篇关于将run()的绑定/管道输出打开/插入到python3(lynux)函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!