【问题标题】:Gather constant output from process (Python) [duplicate]从流程(Python)收集恒定输出[重复]
【发布时间】:2014-12-16 13:55:36
【问题描述】:

我有一个生成恒定输出的程序 (hcitool lescan):

CC:41:00:4D:AA:AA Name1
CC:41:00:4D:AA:BB Name2
CC:41:00:4D:AA:CC Name3

我想不断地在Python 中解析这个输出,但是几秒钟后我想终止进程。 由于它必须手动终止(按CTRL-C),我不能使用subprocess.check_value(["prog"])。也调用p = subprocess.Popen(["prog"], stdout=subprocess.PIPE) 不好,因为它命令Popen 将其读给EOF。此外,这样的调用会挂起Python 脚本。

我的问题是:如何在Python 中启动一个程序(可以限制为Linux 环境)并在几秒钟后在收集它的输出(来自stdout)时终止它?

【问题讨论】:

标签: python subprocess stdout popen bluez


【解决方案1】:

根据您的程序正在做什么,您可以使用几种方法。

第一个是将进程置于一个while循环中并检查lescan输出文件中的MAC地址。

import os

tag = 0
while tag != "00:11:22:33:44:55":
    open("file.txt","w").close()
    os.system("hcitool lescan> file.txt"+" & pkill --signal SIGINT hcitool")
    f = open("file.txt","r")
    read = f.read()
    if "00:11:22:33:44:55" in read:
        print "found"
        tag = "00:11:22:33:44:55"
print "program finished"
os._exit(0)

第二种解决方案是如果您同时使用lescanhcidump

import time
import os
import subprocess

d = subprocess.Popen(["sudo hcitool lescan --duplicates & sudo hcidump -w dump.txt"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
time.sleep(3)
dump = os.system("sudo hcidump -r dump.txt>scan.txt")
#read the file like the previous solution I shown you
print "program finished"
os._exit(0)

我发现做到这一点的最佳方法是将您的读数输出到一个文件中,然后扫描该文件以查找您正在寻找的任何特定内容。

如果您需要任何具体的内容,请回复评论,尽管我想我已经回答了您的问题。

【讨论】:

  • 1.您使用os.system() 调用的第一个解决方案会杀死hcitool 立即。它不是很有用。 2. 我不知道你想通过在这里使用hcidump 来实现什么,但除非你从管道中读取,否则不要使用stdout=PIPE 3. 除非你需要它,否则不要使用shell=True。 4. 删除os._exit(0),它在这里做了错误的事情,例如,它不会刷新标准输出,并且在这里是不必要的。 5.here're possible alternative solutions.
【解决方案2】:

只要您正在运行的子流程持续产生输出,这应该可以工作。您可以随时使用 Ctrl-C 结束它。

(结合 J.F. Sebastian 的明智建议)

import subprocess

p = subprocess.Popen(['hcitool', 'lescan'],stdout=subprocess.PIPE,bufsize=1)

try:
    for line in iter(p.stdout.readline, ""):
        print line, # Do watever processing you want to do here
except KeyboardInterrupt:
    p.kill()

p.wait()
p.stdout.close()

【讨论】:

  • 这是一种糟糕的编码习惯,@Melon 明确表示他想要一个计时器,然后让程序在一定的秒数后停止。意思是,程序应该是自动化的,没有键盘输入。
  • 我不是这样阅读他的问题的。我将其解释为他希望能够在几秒钟后停止它。也许我误解了。不管怎样,我看不出这与编码实践有什么关系。
  • 用 CTRL-C 杀死一个程序是不好的做法,所有程序都应该是自我高效的并在正确的时间终止。 os._exit(0) 在完成其进程后退出任何程序,而不使用 CTRL-C。 @Moose
  • 你没有杀死 Python 程序。它可以愉快地继续运行。您正在发送一个中断,告诉它终止子进程。我可以看到很多用处。
  • @JonathanDavies:OP 错误地认为Ctrl-C 是强制在几秒钟内杀死子进程的。因此@Moose 的答案是(不正确但)对问题的可能解释
猜你喜欢
  • 2021-01-04
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多