I want to start a web server via Python. When this succeeds, I want to open the page in the default browser (on macOS, you can do this with the open command), and after that, I want to resume the previous script again.

This does not work:

#!/usr/bin/env bash
cd wwwroot
python3 -m http.server &
fg 1

I could not use jobs, and open the URL, and after that just run the Python script. However, I don't want to reload the page of the URL. Python will continue to run, until stopped by Ctrl+C.

Perhaps, the open command needs to have a sleep command when Python is not ready yet...

  • try python3 -m http.server && open the && means run whatever command is next if the first one succeeds
    – Bart
    Jun 14, 2019 at 20:56
  • Python will stay active until ctrl+c is hit...
    – doekman
    Jun 14, 2019 at 20:59
  • Do the script work as desired when typed interactively line-by-line into the terminal?
    – Randall
    Jun 14, 2019 at 21:07
  • Not completely. It says ` fg: no job control`. Is there a programmatic way to get the job_spec into a variable, so it can be used later, without relying on sed or such? (I have a hard time reading the bash manual)
    – doekman
    Jun 15, 2019 at 12:34

1 Answer 1


After some experimentation, it seems that $! is the variable you want. Example:

(sleep 1 && open &
disown $!
python3 -m http.server

The sleep makes sure (well, very likely at least) the server is up-and-running before the open is executed. However, there's still the potential for failure if python3 -m http.server takes longer than a second – make certain to document this possibility.

  • 1
    Too quick. $! is the pid (process identifier), but fg needs jobspec...
    – doekman
    Jun 15, 2019 at 15:39
  • I now do this: (sleep 1 && open &; disown $!; python3 -m http.server
    – doekman
    Jun 15, 2019 at 15:43
  • @doekman That's asking for a race condition, but it might be good enough. Could you post it as an answer so I can delete this one?
    – wizzwizz4
    Jun 15, 2019 at 16:38
  • I can just edit this answer (your $! contribution made me think of this). What do you mean by "race condition"? I can't see any reason why that should occur. If python is really slow, the open statement will cause Safari to say: "could not find server".
    – doekman
    Jun 17, 2019 at 8:31
  • 1
    @doekman Yes, that's what I mean. If that's not a problem, why have the wait at all? And if it is, but not a very big one, make sure you document it.
    – wizzwizz4
    Jun 17, 2019 at 17:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .