windows 带有隐藏窗口的跨平台子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1016384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:40:07  来源:igfitidea点击:

Cross-platform subprocess with hidden window

pythonwindowslinuxcross-platformsubprocess

提问by endolith

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 STARTUPINFO, while this isn't valid in Linux:

我想在后台打开一个进程并与之交互,但是这个进程在Linux和Windows中应该是不可见的。在 Windows 中,您必须使用 STARTUPINFO 做一些事情,而这在 Linux 中无效:

ValueError: startupinfo is only supported on Windows platforms

ValueError:startupinfo 仅在 Windows 平台上受支持

Is there a simpler way than creating a separate Popen command for each OS?

有没有比为每个操作系统创建单独的 Popen 命令更简单的方法?

if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
    proc = subprocess.Popen(command)    

采纳答案by Anurag Uniyal

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)

回答by goertzenator

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

刚一说明:用于Python的2.7我必须使用subprocess._subprocess.STARTF_USESHOWWINDOW替代subprocess.STARTF_USESHOWWINDOW

回答by SpliFF

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.

我不确定你能得到比你所做的更简单的事情。您正在谈论优化 5 行代码。为了钱,我会继续我的项目并接受这是跨平台开发的结果。如果你经常这样做,那么创建一个专门的类或函数来封装逻辑并导入它。

回答by Nicolas Dumazet

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.

但这也好不到哪里去。