Cross-platform subprocess with hidden window

后端 未结 4 1076
陌清茗
陌清茗 2020-11-28 08:18

I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with S

相关标签:
4条回答
  • 2020-11-28 08:26

    I'm not sure you can get much simpler than what you've done. You're talking about optimising out maybe 5 lines of code. For the money I would just get on with my project and accept this as a consquence of cross-platform development. If you do it a lot then create a specialised class or function to encapsulate the logic and import it.

    0 讨论(0)
  • 2020-11-28 08:34

    You can turn your code into:

    params = dict()
    
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        params['startupinfo'] = startupinfo
    
    proc = subprocess.Popen(command, **params)
    

    but that's not much better.

    0 讨论(0)
  • 2020-11-28 08:39

    You can reduce one line :)

    startupinfo = None
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    proc = subprocess.Popen(command, startupinfo=startupinfo)
    
    0 讨论(0)
  • 2020-11-28 08:49

    Just a note: for Python 2.7 I have to use subprocess._subprocess.STARTF_USESHOWWINDOW instead of subprocess.STARTF_USESHOWWINDOW.

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