如何在 Python 中打开外部程序中的文件?

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

How can I open files in external programs in Python?

python

提问by

I'm wondering how to open files in programs such as Notepad and Picture Viewer depending on the extension the file has. I'm using Python 3.3 on Windows.

我想知道如何根据文件的扩展名在记事本和图片查看器等程序中打开文件。我在 Windows 上使用 Python 3.3。

I've done some research and people have mentioned a module named Image, but when I try and import this module I get an ImportError.

我做了一些研究,人们提到了一个名为 的模块Image,但是当我尝试导入这个模块时,我得到了一个 ImportError。

Here's what I have so far:

这是我到目前为止所拥有的:

def openFile():
    fileName = listbox_1.get(ACTIVE)
    if fileName.endswith(".jpg"):
        fileName.open()

I will also have HTML and JSON files that I will need to open in Notepad.

我还需要在记事本中打开 HTML 和 JSON 文件。

采纳答案by

Use this to open any file with the default program:

使用它可以使用默认程序打开任何文件:

import os
def openFile():
    fileName = listbox_1.get(ACTIVE)
    os.system("start " + fileName)

If you really want to use a certain program, such as notepad, you can do it like this:

如果你真的想使用某个程序,比如记事本,你可以这样做:

import os
def openFile():
    fileName = listbox_1.get(ACTIVE)
    os.system("notepad.exe " + fileName)

Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.

此外,如果您在打开文件之前需要一些 if 检查,请随意添加它们。这仅向您展示如何打开文件。

回答by Zack Yoshyaro

Expanding on FatalError's suggestion with an example.

用一个例子扩展 FatalError 的建议。

One additional benefit of using subprocessingrather than os.systemis that it uses the same syntax cross-platform (os.systemon Windows requires a "start" at the beginning, whereas OS X requires and "open". Not a huge deal, but one less thing to remember).

使用subprocessing而不是的另一个好处os.system是它使用相同的跨平台语法(os.system在 Windows 上需要在开始时“开始”,而 OS X 需要“打开”。没什么大不了的,但要记住的事情少了一点) .

Opening a file with subprocess.call.

subprocess.call.打开文件

All you need to do to launch a program is call subprocess.call()and lass in a listof arguments where the first is the path to the program, and the rest are additional arguments that you want to supply to the program you're launching.

启动程序所需要做的就是subprocess.call()list参数a中调用和 lass,其中第一个是程序的路径,其余是您要提供给正在启动的程序的附加参数。

For instance, to launch Notepad.exe

例如,启动 Notepad.exe

import subprocess
import os


path_to_notepad = 'C:\Windows\System32\notepad.exe'
path_to_file = 'C:\Users\Desktop\hello.txt'

subprocess.call([path_to_notepad, path_to_file])

Passing multiple arguments and paths is equally as simple. Just add additional items to the list.

传递多个参数和路径同样简单。只需将其他项目添加到列表中即可。



Launching with multiple arguments

使用多个参数启动

This, for example, launches a JAR file using a specific copy of the Java runtime environment.

例如,这会使用 Java 运行时环境的特定副本启动 JAR 文件。

import subprocess
import os

current_path = os.getcwd()
subprocess.call([current_path + '/contents/home/bin/java', # Param 1
                    '-jar', #Param2
                    current_path + '/Whoo.jar']) #param3

Argument 1 targets the program I want to launch. Argument2 supplies an argument tothat program telling it that it's going to run a JAR, and finally Argument3 tells the target program where to find the file to open.

参数 1 的目标是我要启动的程序。ARGUMENT2提供的参数,以该程序告诉它它会运行一个JAR,最后参数3告知目标程序在哪里可以找到要打开的文件。

回答by jfs

On Windows you could use os.startfile()to open a file using default application:

在 Windows 上,您可以使用os.startfile()默认应用程序打开文件:

import os
os.startfile(filename)

There is no shutil.open()that would do it cross-platform. The close approximation is webbrowser.open():

没有shutil.open()那个可以跨平台的。最接近的近似值是webbrowser.open()

import webbrowser
webbrowser.open(filename)

that might use automatically opencommand on OS X, os.startfile()on Windows, xdg-openor similar on Linux.

可能open在 OS X、os.startfile()Windowsxdg-open或 Linux 上的类似命令上使用自动命令。

If you want to run a specific application then you could use subprocessmodulee.g., Popen()allows to start a program without waiting for it to complete:

如果你想运行一个特定的应用程序,那么你可以使用subprocess模块,例如,Popen()允许在不等待程序完成的情况下启动程序:

import subprocess

p = subprocess.Popen(["notepad.exe", fileName])
# ... do other things while notepad is running
returncode = p.wait() # wait for notepad to exit

There are many ways to use the subprocessmodule to run programs e.g., subprocess.check_call(command)blocks until the command finishes and raises an exception if the command finishes with a nonzero exit code.

有很多方法可以使用subprocess模块来运行程序,例如,subprocess.check_call(command)阻塞直到命令完成,如果命令以非零退出代码结束则引发异常。