How do I hide the console when I use os.system() or subprocess.call()?

后端 未结 5 494
难免孤独
难免孤独 2020-11-22 07:58

I wrote some statements like below:

os.system(cmd) #do something
subprocess.call(\'taskkill /F /IM exename.exe\')

both will pop up a consol

相关标签:
5条回答
  • 2020-11-22 08:32

    Add the shell=True argument to the subprocess calls.

    subprocess.call('taskkill /F /IM exename.exe', shell=True)
    

    Or, if you don't need to wait for it, use subprocess.Popen rather than subprocess.call.

    subprocess.Popen('taskkill /F /IM exename.exe', shell=True)
    
    0 讨论(0)
  • 2020-11-22 08:33

    Just add: subprocess.call('powershell.exe taskkill /F /IM exename.exe', shell=True)

    0 讨论(0)
  • 2020-11-22 08:51

    Try to change the extension from .py to .pyw

    Its basically just a Python User Interface file. So it opens up a new Window without the command line. chech this link (filext.com/file-extension/PYW)

    0 讨论(0)
  • 2020-11-22 08:54

    Try subprocess.Popen(["function","option1","option2"],shell=False).

    0 讨论(0)
  • 2020-11-22 08:55

    The process STARTUPINFO can hide the console window:

    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    #si.wShowWindow = subprocess.SW_HIDE # default
    subprocess.call('taskkill /F /IM exename.exe', startupinfo=si)
    

    Or set the creation flags to disable creating the window:

    CREATE_NO_WINDOW = 0x08000000
    subprocess.call('taskkill /F /IM exename.exe', creationflags=CREATE_NO_WINDOW)
    

    The above is still a console process with valid handles for console I/O (verified by calling GetFileType on the handles returned by GetStdHandle). It just has no window and doesn't inherit the parent's console, if any.

    You can go a step farther by forcing the child to have no console at all:

    DETACHED_PROCESS = 0x00000008
    subprocess.call('taskkill /F /IM exename.exe', creationflags=DETACHED_PROCESS)
    

    In this case the child's standard handles (i.e. GetStdHandle) are 0, but you can set them to an open disk file or pipe such as subprocess.DEVNULL (3.3) or subprocess.PIPE.

    0 讨论(0)
提交回复
热议问题