process.py 2.54 KB
Newer Older
Melroy van den Berg's avatar
Melroy van den Berg committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import asyncio
import sys
from time import sleep
from asyncio.subprocess import PIPE, STDOUT

TIMEOUT_TO_ACTIVATE_PLUGIN=25 #secs

def process_line(line):
    """
    Check if MOZREPL is in the stdout line
    """
    return b"MOZREPL" in line

async def run_command(*args, timeout=None):
    """
    Start process with timeout durinf the readout of stdout
    """
    return_code = 0
    # Start Firefox process
    process = await asyncio.create_subprocess_exec(*args,
            stdout=PIPE)

    # read line (sequence of bytes ending with b'\n') asynchronously
    mozrepl_found=False
    while True:
        try:
            line = await asyncio.wait_for(process.stdout.readline(), timeout)
        except asyncio.TimeoutError:
            if mozrepl_found:
                pass
            else:
                print("Mozrepl was not detected in time (time-out)!\nDid you install and enable Mozrepl plugin in Firefox? (Install: https://addons.mozilla.org/nl/firefox/addon/mozrepl/).\n\nTry again.")
                try:
                    process.kill()
                    await process.wait()
                except ProcessLookupError:
                    pass
                return_code=1
                break
        else:
            if not line: # EOF
                # Firefox is closed.
                try:
                    process.kill()
                    await process.wait()
                    print("You closed Firefox. That was not the idea...")
                    return_code=1
                    break
                except ProcessLookupError:
                    print("Firefox process has already started earlier, be sure you enable Mozrepl. Waiting " + str(TIMEOUT_TO_ACTIVATE_PLUGIN) + " seconds before I try to connect to mozrepl...")                    
                    sleep(TIMEOUT_TO_ACTIVATE_PLUGIN)
                    break
            elif process_line(line): 
                # mozrepl is loaded/found!
                mozrepl_found=True
                break
            else:
                # Required line not found
                continue
    return return_code

def startFirefox():
    """
    Start Firefox process with our own HTML page
    return status - 0 is OK 1 is NOK
    """
    if sys.platform == "win32":
        loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.get_event_loop()

    status = loop.run_until_complete(
        run_command("firefox", "site/index.html", timeout=180))
    if status:
        loop.close()
    return status