stdout.readline() 如果stdout中没有数据,子进程的语句就会卡住。如何打破循环? [重复]

问题描述 投票:0回答:1

我正在尝试从

readline
stdout
subprocess
。有时设备“123”没有响应,也不会在
stdout
中提供和数据。在那种情况下,
out = proc.stdout.readline()
线会永远卡住。如果设备没有响应,如何退出循环。

我正在尝试阅读子流程的

stdout
。下面是代码。

cmd = ["node", "transformerMonitor.js", "-h", "sample.com", "-s", "123"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True)
time_out = 120
start_time = time.time()
while time.time() - start_time < time_out:
    out = proc.stdout.readline()
    print(out)

如果设备没有响应。

out = proc.stdout.readline()
永远卡住了。如果没有响应,如何打破循环。

python node.js subprocess stdout
1个回答
0
投票

一旦子进程完成/失败并且设备不再有响应,

out
将是一个空字符串。我们可以利用这个事实跳出循环。

代码:

import subprocess
import time

cmd = ["node", "transformerMonitor.js", "-h", "sample.com", "-s", "123"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True)
time_out = 120
start_time = time.time()
while time.time() - start_time < time_out:
    out = proc.stdout.readline()
    # If empty string output (No Response from Device), break out of loop.
    if not out:
        break
print('Code Finished')

输出:

node:internal/modules/cjs/loader:998
  throw err;
  ^

Error: Cannot find module 'C:\Users\sapta\Documents\testing\transformerMonitor.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)        
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v18.12.1
Code Finished
© www.soinside.com 2019 - 2024. All rights reserved.