windows windows下运行快捷方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/349653/
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 11:43:04  来源:igfitidea点击:

Run a shortcut under windows

pythonwindows

提问by Mapad

The following doesn't work, because it doesn't wait until the process is finished:

以下不起作用,因为它不会等到过程完成:

import subprocess
p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True)
p.wait()

Any idea how to run a shortcut and wait that the subprocess returns ?

知道如何运行快捷方式并等待子进程返回吗?

Edit:originally I was trying this without the shelloption in my post, which caused Popen to fail. In effect, startis not an executable but a shell command. This was fixed thanks to Jim.

编辑:最初我在我的帖子中没有shell选项的情况下尝试这个,这导致 Popen 失败。实际上,start它不是一个可执行文件,而是一个 shell 命令。多亏了 Jim,这个问题得到了解决。

回答by JimB

You will need to invoke a shell to get the subprocess option to work:

您将需要调用一个 shell 来使 subprocess 选项起作用:

p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True)
p.wait()

This however will still exit immediately (see @R. Bemrose).

然而,这仍然会立即退出(见@R. Bemrose)。

If p.pidcontains the correct pid (I'm not sure on windows), then you could use os.waitpid()to wait for the program to exit. Otherwise you may need to use some win32 com magic.

如果p.pid包含正确的 pid(我不确定在 Windows 上),那么您可以os.waitpid()用来等待程序退出。否则,您可能需要使用一些 win32 com 魔法。

回答by Powerlord

cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ):

cmd.exe 在 start 启动程序后立即终止。此行为已记录在案(在 start /? 中):

If Command Extensions are enabled, external command invocation through the command line or the START command changes as follows:

如果启用了命令扩展,则通过命令行或 START 命令进行的外部命令调用更改如下:

...

...

When executing an application that is a 32-bit GUI application, CMD.EXE does not wait for the application to terminate before returning to the command prompt. This new behavior does NOT occur if executing within a command script.

执行 32 位 GUI 应用程序时,CMD.EXE 不会等待应用程序终止,然后返回到命令提示符。如果在命令脚本中执行,则不会发生这种新行为。

How this is affected by the /wait flag, I'm not sure.

这如何受 /wait 标志的影响,我不确定。

回答by rob

Note: I am simply adding on Jim's reply, with a small trick. What about using 'WAIT' option for start?

注意:我只是通过一个小技巧添加了 Jim 的回复。使用“WAIT”选项启动怎么样?

p = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True)
p.wait()

This should work.

这应该有效。