17

ファイルの拡張子によっては、メモ帳やピクチャ ビューアーなどのプログラムでファイルを開く方法が気になります。WindowsでPython 3.3を使用しています。

私はいくつかの調査を行い、人々は という名前のモジュールについて言及しましたImageが、このモジュールをインポートしようとすると、ImportError が発生します。

これが私がこれまでに持っているものです:

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

また、メモ帳で開く必要がある HTML ファイルと JSON ファイルもあります。

4

3 に答える 3

29

Windows ではos.startfile()、デフォルトのアプリケーションを使用してファイルを開くために使用できます。

import os
os.startfile(filename)

shutil.open()クロスプラットフォームでそれを行うものはありません。近似値は次のwebbrowser.open()とおりです。

import webbrowser
webbrowser.open(filename)

openOS X、os.startfile()Windows、xdg-openまたは Linux で同様のコマンドを自動的に使用する可能性があります。

特定のアプリケーションを実行したい場合は、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

subprocessモジュールを使用してプログラムを実行する方法は多数あります。たとえば、subprocess.check_call(command)コマンドが終了するまでブロックし、コマンドがゼロ以外の終了コードで終了した場合は例外を発生させます。

于 2013-02-24T18:37:29.463 に答える
12

これを使用して、既定のプログラムで任意のファイルを開きます。

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

メモ帳などの特定のプログラムを使用したい場合は、次のようにします。

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

また、ファイルを開く前に if チェックが必要な場合は、気軽に追加してください。これは、ファイルを開く方法のみを示しています。

于 2013-02-24T17:35:02.980 に答える
5

Expanding on FatalError's suggestion with an example.

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

Opening a file with subprocess.call.

All you need to do to launch a program is call subprocess.call() and pass in a list of 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.

For instance, to launch Notepad.exe

import subprocess    

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.

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 to that 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.

于 2013-02-24T18:15:34.107 に答える