1

I am trying to readline from stdout of subprocess. Sometimes device "123" doesn't respond and won't provide and data in stdout. In that case line out = proc.stdout.readline() is getting stuck forever. How to come out of loop if there is no response from device.

I am trying to read stdout of a subprocess. below is the code.

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)

if device doesn't respond. out = proc.stdout.readline() is stuck forever. How to break the loop if there is no response.

cards
  • 3,936
  • 1
  • 7
  • 25
  • 1
    just to know `proc.wait` and `proc.communicate` [doc](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.wait) have a `timeout` parameter and processes may receive signals – cards Apr 08 '23 at 16:56
  • 1
    Does this answer your question? [Using module 'subprocess' with timeout](https://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout) – Davis Herring Apr 09 '23 at 06:55

1 Answers1

0

Once the subprocess finishes/fails and there are no more responses from the device, out will be an empty string. We can break out of the loop using this fact.

Code:

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')

Output:

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
halfer
  • 19,824
  • 17
  • 99
  • 186
SaptakD625
  • 89
  • 4