1

Hoping someone can help with this:

def non_block_read(output):

    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read()
    except:
        return ''

def trace(stdout):
    while True:
        output = non_block_read(stdout).strip()
        if output:
            defaults.app.logger.info(output)
            defaults.socketio.emit("traceroute", {"Data": output})

tracerouteHost = '127.0.0.1'
hops = data['hops'] if data['hops'] else 32

if re.match('^[a-zA-Z0-9.-]{2,200}$', data['host']):
    tracerouteHost = data['host']


p = Popen(["traceroute", tracerouteHost, "-m", str(hops)], stdout=PIPE, stderr=PIPE)
thread = threading.Thread(target=trace, args=[p.stdout])
thread.daemon = True
thread.start()

The problem is this "appears" to work but all the output of the traceroute command isn't being capture, only some of it.

I found most of this on the web so don't fully understand it.

Basically I'm trying to make it so I run a traceroute command in the background and as I get output from it, I want to send it out my web socket (socketio) to the browser.

But I don't want it to block other actions.

I'm using Python Flask/Gevent if that's any help for anyone.

Charlie
  • 1,646
  • 5
  • 22
  • 40
  • If you are using gevent, then reading from a pipe is non-blocking, you do not need to do any complicated stuff with `fcntl` to read the output of your subprocess. If you just do `stdout.readline()` in your `trace` function your read will block the thread, but other threads will run in the meantime. – Miguel Grinberg Jan 23 '16 at 18:18

0 Answers0