How to make a python program open itself as text in safari?
Question: I was trying to make a program in Python that would use os.system to open a
file in Safari. In this case, I was trying to have it open a text copy of
itself. The files name is foo.py.

    
    
    import os, socket
    os.system("python -m SimpleHTTPServer 4000")
    IP = socket.gethostbyname(socket.gethostname())
    osCommand = "open -a safari http://"+IP+":4000/foo.py"
    os.system(osCommand)
    


Answer: [`system`](https://docs.python.org/2/library/os.html#os.system) runs a
program, then waits for it to finish, before returning.

So it won't get to the next line of your code until the server has finished
serving. Which will never happen. (Well, you can hit ^C, and then it will stop
serving—but then when you get to the next line that opens `safari`, it'll have
no server to connect to anymore.)

This is one of the many reasons the docs for `system` basically tell you not
to use it:

> The [`subprocess`](https://docs.python.org/2/library/subprocess.html#module-
> subprocess) module provides more powerful facilities for spawning new
> processes and retrieving their results; using that module is preferable to
> using this function. See the [_Replacing Older Functions with
> the`subprocess`
> Module_](https://docs.python.org/2/library/subprocess.html#subprocess-
> replacements) section in the `subprocess` documentation for some helpful
> recipes.

For example:

    
    
    import subprocess, socket
    server = subprocess.Popen(['python', '-m', 'SimpleHTTPServer', '4000'])
    IP = socket.gethostbyname(socket.gethostname())
    safari = subprocess.Popen(['open', '-a', 'safari', 'http://'+IP+':4000/foo.py'])
    server.wait()
    safari.wait()
    

That will start both programs in the background, and then wait for both to
finish, instead of starting one, waiting for it to finish, starting the other,
and waiting for it to finish.

* * *

All that being said, this is kind of a silly way to do what you want. What's
wrong with just opening a file URL (like
`'file:///{}'.format(os.path.abspath(sys.argv[0]))`) in Safari? Or in the
default web browser (which would presumably be Safari for you, but would also
work on other platform, and for Mac users who used Chrome or Firefox, and so
on) by using `webbrowser.open` on that URL?

