使用 Python 执行 windows 中的文件

Execute files in windows with Python

我想让我的 python 程序执行 Windows 中的文件。这意味着如果我尝试执行 .txt 文件,它将使用默认的 .txt 查看器打开。这可能吗?

我尝试了 subprocess.call,但我得到了 WindowsError: [Error 193] %1 is not a valid Win32 application。我尝试 运行 的文件是 .png 文件。

假设您有一个文件 myText.txt
如果你想通过命令行打开那个文件,你可以简单地写 ~$ myText.txt.
所以在 Python 中,你可以只 运行 一个打开文件的 cmd 命令。说:

import os
os.system("myText.txt") #Requires myText.txt and the python file to be in same folder. Otherwise full path is required.

这将在默认编辑器中打开文件,或者如果它是一个 exe 文件,只需 运行 它。

这将使用 .txt 扩展名的注册应用程序启动文件:

import os
os.system("start myText.txt")

您需要使用子流程

subprocess.call("start myText.txt", shell=True)

因为 start 是 shell 的一部分。

os.startfile("myText.txt") #open text editor
os.startfile("myText.pdf") #open in pdf viewer
os.startfile("myText.html") #open in webbrowser

你应该怎么做

然而

os.startfile("my_prog.py")

可能是一个错误的 idea,因为无法知道 python 是否设置为打开 *.py 的默认值,或者是否设置了文本编辑器或 ide作为默认打开 *.py