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.

0

3 Answers 3

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 " ) 
Sign up to request clarification or add additional context in comments.

3 Comments

If python exits, the child process might be quit too. Adding a nohup might do it, though.
Add nohup or just add disown after &.
how is this for crossplatformness?
0
import subprocess import os with open(os.devnull, 'w') as f: proc = subprocess.Popen(command, shell=True, stdout=f, stderr=f) 

4 Comments

thanks for reading my op. :) this spawns a child process, not a full process
Perhaps I'm not understanding your question. Can you give an example when this does not satisfy your requirements?
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
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.
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() 

2 Comments

This seems a bit complicated if I still have to do something else for windows but ill try it
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.