在没有 shell 窗口的情况下运行 shell 命令 [英] Running shell commands without a shell window

查看:72
本文介绍了在没有 shell 窗口的情况下运行 shell 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用subprocess.callsubprocess.Popen,执行shell 命令会使shell 窗口快速出现和消失.

如何在没有 shell 窗口的情况下运行 shell 命令?

解决方案

我想您的观察仅限于 Windows,因为我相信 Windows 是您会遇到控制台闪存"问题的唯一平台.如果是这样,那么 docs 提供以下半有用的段落:

<块引用>

startupinfo 和 creationflags,如果给定,将传递给底层 CreateProcess() 函数.他们可以指定诸如主窗口的外观和新进程的优先级.(视窗仅)

不幸的是,Python 在线文档没有重现 Windows API 文档的相关部分,因此您必须在其他地方找到它们,例如在 MSDN 上这里开始引导您creationflags ="http://msdn.microsoft.com/en-us/library/ms684863(v=VS.85).aspx" rel="noreferrer">此处,特别是

CREATE_NO_WINDOW0x08000000

<块引用>

进程是一个控制台应用程序在没有控制台的情况下运行窗户.因此,控制台句柄未设置应用程序.

因此,将 creationflags=0x08000000 添加到您的 Popen 调用应该会有所帮助(不幸的是,我没有运行 Windows 的机器可以尝试此操作,因此您将有自己试试).

With either subprocess.call or subprocess.Popen, executing a shell command makes a shell window quicky appear and disappear.

How can I run the shell command without the shell window?

解决方案

I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that "console flash" issue. If so, then the docs offer the following semi-helpful paragraph:

The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only)

Unfortunately the Python online docs do not reproduce the relevant portion of the Windows API docs, so you have to locate those elsewhere, e.g. starting here on MSDN which leads you here for the creationflags, and specifically to

CREATE_NO_WINDOW
0x08000000

The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set.

So, adding creationflags=0x08000000 to your Popen call should help (unfortunately I have no Windows-running machine on which to try this out, so you'll have to try it yourself).

这篇关于在没有 shell 窗口的情况下运行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆