【问题标题】:Unable to launch windows shortcut无法启动 Windows 快捷方式
【发布时间】:2017-01-31 09:22:40
【问题描述】:

我正在尝试使用 python 启动一个窗口。我已经用 os.system、subprocess.call、os.startfile 等尝试过无数种方法,但我总是收到一条错误消息,提示路径不存在。

我知道路径是正确的,因为我尝试在 CMD.EXE 中运行以下命令:

start D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk

以下是我尝试过但没有成功的一些东西:

os.startfile(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")
os.startfile("D:\\johan\\programmering\\Scripts\\shortcuts\\HWMonitor.lnk")
subprocess.call("D:\\johan\\programmering\\Scripts\\shortcuts\\HWMonitor.lnk")
subprocess.call(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")
subprocess.Popen(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")
subprocess.Popen(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk", shell=True)
os.system(r"start D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")

p= subprocess.Popen(r"start D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk", shell=True)
p.wait()

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")
subprocess.call(shortcut.Targetpath)

免责声明我知道在 SO 上有类似的问题,但没有一个对我有帮助。所以在你开始喊“重复!”之前请知道我已经尝试了没有成功的解决方案。

【问题讨论】:

  • @Aaron 已经尝试过了。
  • @Aaron 我现在已将我的尝试添加到问题中。我做错了什么?
  • os.startfile 应该可以工作,subprocess.Popenshell=True 的朋友也应该可以工作——因为在这两种情况下,您最终都会调用 ShellExecute[Ex],即了解如何打开 .lnk 文件的 shell API . CreateProcess(由 Popen 调用)对 .lnk 快捷方式一无所知,因此,如果您需要使用带有 Popen 而没有 shell=True 的快捷方式(并且仅在这种情况下),那么您必须提取使用 shell COM 接口的快捷方式中的目标和工作目录。
  • 尝试通过subprocess.call直接运行可执行文件,通过C:和D:驱动器路径,有和没有shell=True。例如,subprocess.call([r'C:\Program Files (x86)\CPUID\HWMonitor\HWMonitor.exe'])

标签: python windows


【解决方案1】:

根据这个answer,你可以解析你的链接路径,然后调用解析的路径

import sys
import win32com.client,win32api

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(r"D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk")
long_path = shortcut.Targetpath

但是long_path 可能是一个奇怪的 Windows 路径,里面有很多垃圾,所以如果

subprocess.call([long_path])

不行,可以用短路径解析长路径(8.3名称):

short_path=win32api.GetShortPathName(long_path)

现在做:

subprocess.call([short_path])

【讨论】:

  • 在安装模块时遇到一些麻烦,一旦我设法让模块工作,我会回到这个答案。
  • 好的!所以我设法让 win32com.client 工作,我正在使用你的确切答案,但我仍然收到FileNotFoundError: [WinError 2] The system cannot find the file specified
  • 好的,你能打印shortcut.Targetpath吗?你确定你的链接指向一个有效的文件吗?,还要检查我的编辑
  • 我无法打印快捷方式。目标路径(同样的错误),我已经尝试过你更新的答案(同样的错误),正如我在问题中所说,如果我只运行 start D:\johan\programmering\Scripts\shortcuts\HWMonitor.lnk 就可以了在 CMD.EXE 中,所以是的。路径应该是正确的
  • 打印时出现同样的错误??哪个错误? print 应该可以正常工作
猜你喜欢
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 2011-10-23
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多