繁体   English   中英

使用 Python 的子进程模块读取 Linux 终端输出

[英]read Linux terminal output using Python's sub process module

我在 Linux 终端上运行 python,它需要在测试运行时运行一些 bash 命令。 所以,我正在使用 subprocess 模块并运行我的测试命令(bash 脚本)。 这些所谓的 bash 命令可能会在 CLI 上打印一些我需要知道的东西,当我并行运行我的 python 代码时。

例如:

# running my python TCP server 

subprocess.call(['.\run_some_shell_commands.sh'],shell=True)

while True:
   # I am doing some other python stuff 

   if (CLI_HAS_SOME_OUTPUT_DETECTED):
       #record the output to some variable 


   # doing some more python stuff 


如果我确定run_some_shell_commands.sh肯定会返回一些输出,我可以简单地使用A = subprocess.checkoutput(['.\\run_some_shell_commands.sh'],shell=True)将其输出保存在变量A ..

有没有办法抓取终端的最后 n 行? 这样我就可以检查该事件是否发生了,我可以将其分配给 CLI_HAS_SOME_OUTPUT_DETECTED

任何建议都非常感谢。

赛拉

import subprocess
import time as t
cmd = [' ']
P = subprocess.check_output(cmd,shell=True)
while True :
        print(P)
        t.sleep(0.1)

这在Running shell command and capture the output 中得到了回答。 有两类 shell 命令,可执行文件内置命令,在某些编程语言中,这可能会有所不同,请参阅如何在 android studio 中侦听 shell 命令的响应?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM