本文介绍了是否有与 os.startfile() 等价的平台独立等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多个平台(包括 Mac OS)上运行一个程序,所以我尽量让它保持平台独立.我自己使用 Windows,我有一行 os.startfile(file).这对我有用,但不适用于其他平台(我在文档中阅读过,我还没有为自己测试过).

I want to run a program on several platforms (including Mac OS), so I try to keep it as platform independent as possible. I use Windows myself, and I have a line os.startfile(file). That works for me, but not on other platforms (I read in the documentation, I haven't tested for myself).

是否有适用于所有平台的等价物?

Is there an equivalent that works for all platforms?

顺便说一下,该文件是一个 .wav 文件,但我希望用户能够使用他们的标准媒体播放器,以便他们可以暂停/倒带文件.这就是我使用 os.startfile() 的原因.我或许可以使用还允许播放/暂停/倒带媒体文件的库.

By the way, the file is a .wav file, but I want users to be able to use their standard media player, so they can pause/rewind the file. That's why I use os.startfile(). I might be able to work with libraries that also allow playing/pausing/rewinding media files.

推荐答案

跨平台文件打开模块似乎尚不存在,但您可以依赖流行系统的现有基础架构.此代码段涵盖 Windows、MacOS 和类 Unix 系统(Linux、FreeBSD、Solaris...):

It appears that a cross-platform file opening module does not yet exist, but you can rely on existing infrastructure of the popular systems. This snippet covers Windows, MacOS and Unix-like systems (Linux, FreeBSD, Solaris...):

import os, sys, subprocess

def open_file(filename):
    if sys.platform == "win32":
        os.startfile(filename)
    else:
        opener = "open" if sys.platform == "darwin" else "xdg-open"
        subprocess.call([opener, filename])

这篇关于是否有与 os.startfile() 等价的平台独立等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:37
查看更多