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.

2
  • 1
    just to know proc.wait and proc.communicate doc have a timeout parameter and processes may receive signals Commented Apr 8, 2023 at 16:56
  • 1
    Does this answer your question? Using module 'subprocess' with timeout Commented Apr 9, 2023 at 6:55

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Since there are no new lines/data , line 'out = proc.stdout.readline()' will stuck forever code wont go to next line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.