1

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 &
open http://0.0.0.0:8000
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...

4
  • try python3 -m http.server && open http://0.0.0.0:8000. the && means run whatever command is next if the first one succeeds
    – Bart
    Commented Jun 14, 2019 at 20:56
  • Python will stay active until ctrl+c is hit...
    – doekman
    Commented Jun 14, 2019 at 20:59
  • Do the script work as desired when typed interactively line-by-line into the terminal?
    – Randall
    Commented 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
    Commented Jun 15, 2019 at 12:34

1 Answer 1

2

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

(sleep 1 && open http://0.0.0.0:8000) &
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.

5
  • 1
    Too quick. $! is the pid (process identifier), but fg needs jobspec...
    – doekman
    Commented Jun 15, 2019 at 15:39
  • I now do this: (sleep 1 && open http://0.0.0.0:8000) &; disown $!; python3 -m http.server
    – doekman
    Commented 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
    Commented 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
    Commented 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
    Commented 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 .