使用subprocess打开Notepad.lnk遇FileNotFoundError问题求助
问题原因及解决方法
核心错误原因
start 是Windows系统中cmd.exe的内置命令,并非独立的可执行程序。subprocess.run()默认会把列表第一个元素当作可执行文件路径查找,自然找不到名为start的文件,因此抛出FileNotFoundError。
你的代码还有两个细节问题:
import语句放在if __name__ == '__main__':块内虽语法合法,但不符合Python编码规范,建议移到文件顶部。- 检测到快捷方式不存在时,仅打印错误信息却未终止程序,后续仍会执行
subprocess.run(),可能引发额外错误。
解决方法
方法1:通过cmd /c调用start命令
将start命令作为cmd.exe的参数传入,让系统命令行解释器执行这个内置命令:
import os import subprocess if __name__ == '__main__': cwd = os.getcwd() shortcut_path = os.path.join(cwd, 'Notepad.lnk') if not os.path.exists(shortcut_path): print('Error: "Notepad.lnk" shortcut not found') exit(1) # 终止程序,避免后续执行错误代码 # 使用cmd /c执行start命令,空字符串用于正确解析带空格的路径 subprocess.run(['cmd', '/c', 'start', '', shortcut_path], check=True)
方法2:直接启动记事本(绕开快捷方式)
如果你的目标只是打开记事本,无需依赖快捷方式,可直接调用系统自带的记事本程序:
import subprocess if __name__ == '__main__': subprocess.run(['notepad.exe'], check=True)
方法3:使用os.startfile(Windows专属最优解)
Windows下Python的os模块提供了startfile方法,可直接打开.lnk快捷文件,无需调用cmd:
import os if __name__ == '__main__': cwd = os.getcwd() shortcut_path = os.path.join(cwd, 'Notepad.lnk') if not os.path.exists(shortcut_path): print('Error: "Notepad.lnk" shortcut not found') exit(1) os.startfile(shortcut_path)
内容的提问来源于stack exchange,提问作者Welshy
相关产品推荐
相关产品推荐

