Running a command completely indepenently from scr

2020-07-19 15:25发布

问题:

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.

回答1:

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 " )


回答2:

import subprocess
import os
with open(os.devnull, 'w') as f:
    proc = subprocess.Popen(command, shell=True, stdout=f, stderr=f)


回答3:

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()