Search code examples
pythonpython-3.xasynchronousjekyllpopen

Python Popen() is blocking


I want to write a little python script to automate Jekyll blog creation, but popen() seems to block and not call asynchronously.

The expected behavior would be:

  1. Start jekyll serve --livereload asynchronously
  2. Start firefox-esr http://127.0.0.1:4000 async and wait for it(, or synchronously, this is not relevant in my use case)
  3. After termination of firefox, terminate Jekyll too.
jekyll = subprocess.Popen(['jekyll', 'serve', '--livereload'])
print('This never gets displayed')
time.sleep(3)
firefox = subprocess.Popen(['firefox-esr', 'http://127.0.0.1:4000'])
firefox.wait()
jekyll.terminate()

But this only starts Jekyll and outputs its stdout to the terminal.

This problem only appears with Jekyll. ping or any other command/program i tried work fine.

Any ideas on what I did wrong?


Solution

  • If you are on Linux, you can create a simple bash script for it.

    #!/bin/bash
    
    jekyll serve --livereload & 
    sleep 5
    firefox-esr http://127.0.0.1:4000 &>/dev/null
    
    
    pid=$(pgrep firefox-esr)
    
    while :
    do
        sleep 5
        if [ -z  "$pid" ]
        then
            pkill ruby 2>/dev/null
            echo "Killed jekyll"
            break
        fi
    done
    

    Give this file execution permissions with

    chmod +x filename.sh
    

    Then run this bash script with

    ./filename.sh &
    

    This will make your script run in the background.