Question

Hi I want Thor to start a server - Jekyll / Python / PHP etc then open the browser

However the starting is a blocking task.

Is there a way to create a child process in Thor; or spawn a new terminal window - couldnt see and google gave me no reasonable answers.

My Code

##
# Project Thor File
#
# @use thor list
##
class IanWarner < Thor

##
# Open Jekyll Server
#
# @use thor ian_warner:openServer
##
desc "openServer", "Start the Jekyll Server"
def openServer

    system("clear")
    say("\n\t")

    say("Start Server\n\t")
    system("jekyll --server 4000 --auto")

    say("Open Site\n\t")
    system("open http://localhost:4000")

    say("\n")

end

end
Was it helpful?

Solution

It looks like you are messing things up. Thor is in general a powerful CLI wrapper. CLI itself is in general singlethreaded.

You have two options: either to create different Thor descendents and run them as different threads/processes, forcing open thread/process to wait until jekyll start is running (preferred,) or to hack with system("jekyll --server 4000 --auto &") (note an ampersand at the end.)

The latter will work, but you still are to control the server is started (it may take a significant amount of time.) The second ugly hack to achieve this is to rely on sleep:

say("Start Server\n\t")
system("jekyll --server 4000 --auto &")

say("Wait for Server\n\t")
system("sleep 3")

say("Open Site\n\t")
system("open http://localhost:4000")

Upd: it’s hard to imagine what do you want to yield. If you want to leave your jekyll server running after your script is finished:

  desc "openServer", "Start the Jekyll Server"
  def openServer
    system "clear"
    say "\n\t"

    say "Starting Server…\n\t"
    r, w = IO.pipe
    # Jekyll will print it’s running status to STDERR
    pid = Process.spawn("jekyll --server 4000 --auto", :err=>w) 
    w.close
    say "Spawned with pid=#{pid}"
    rr = ''
    while (rr += r.sysread(1024)) do
     break if rr.include?('WEBrick::HTTPServer#start')
    end 
    Process.detach(pid) # !!! Leave the jekyll running

    say "Open Site\n\t"
    system "open http://localhost:4000"
  end 

If you want to shutdown the jekyll after the page is opened, you are to spawn the call to open as well and Process.waitpid for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top