3

I have recently come across some situations where I want to start a command completely independently, and in a different process then the script, equivalent typing it into a terminal, or more specifically writing the command into a .sh or .desktop and double clicking it. The request I have are:

  • I can close the python window without closing the application.
  • The python window does not display the stdout from the application (you don't want random text appearing in a CLI), nor do I need it!.

Things I have tried:

  • os.system waits.
  • subprocess.call waits.
  • subprocess.Popen starts a subprocess (duh) closing the parent process thus quits the application

And thats basically all you can find on the web! if it really comes down to it I could launch a .sh (or .bat for windows), but that feels like a cheap hack and not the way to do this.

Andy G
  • 19,232
  • 5
  • 47
  • 69
Azsgy
  • 3,139
  • 2
  • 29
  • 40

3 Answers3

2

If you were to place an & after the command when called from os.system, would that not work? For example:

import os
os.system( "google-chrome & disown " )
konsolebox
  • 72,135
  • 12
  • 99
  • 105
a sandwhich
  • 4,352
  • 12
  • 41
  • 62
0
import subprocess
import os
with open(os.devnull, 'w') as f:
    proc = subprocess.Popen(command, shell=True, stdout=f, stderr=f)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 4
    thanks for reading my op. :) this spawns a child process, not a full process – Azsgy Sep 14 '13 at 22:39
  • Perhaps I'm not understanding your question. Can you give an example when this does not satisfy your requirements? – unutbu Sep 15 '13 at 00:42
  • This opens a child process. If the parent process exits with code 0 it is fine, but when I kill it in another way, like closing the terminal, it quits the child process too – Azsgy Sep 15 '13 at 10:57
  • That's odd. If I use `command = 'ls -lRa / > /tmp/out'`, I can run the script, close the terminal, open a new terminal and `ps axu | grep ls` shows `ls -lRa` is still running. – unutbu Sep 15 '13 at 12:13
0

Spawn a child process "the UNIX way" with fork and exec. Here's a simple example of a shell in Python.

import os

prompt = '$ '
while True:
    cmds = input(prompt).split()
    if len(cmds):
        if (os.fork() == 0):
            # Child process
            os.execv(cmds[0], cmds)
        else:
            # Parent process
            # (Hint: You don't have to wait, you can just exit here.)
            os.wait()
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • This seems a bit complicated if I still have to do something else for windows but ill try it – Azsgy Sep 14 '13 at 22:49
  • This works well, I just changed the os.execv(cmds[0], cmds) line to os.system(cmds) and removed the .split(). Sadly, since all of these don't work for windows "command & disown" is easier. – Azsgy Sep 15 '13 at 11:11