我在Python中,我有一个特定文件夹的路径。我想使用该系统的默认文件夹资源管理器打开它。例如,如果它是Windows计算机,我想使用资源管理器,如果它是Linux,我想使用Nautilus或其他默认设置,如果它是Mac,我想使用任何Mac OS的浏览器。
我该怎么做?
答案 0 :(得分:30)
我很惊讶没有人提到将xdg-open
用于* nix ,这对于文件和文件夹都有效:
import os
import platform
import subprocess
def open_file(path):
if platform.system() == "Windows":
os.startfile(path)
elif platform.system() == "Darwin":
subprocess.Popen(["open", path])
else:
subprocess.Popen(["xdg-open", path])
答案 1 :(得分:17)
您可以使用subprocess
。
import subprocess
import sys
if sys.platform == 'darwin':
def openFolder(path):
subprocess.check_call(['open', '--', path])
elif sys.platform == 'linux2':
def openFolder(path):
subprocess.check_call(['xdg-open', '--', path])
elif sys.platform == 'win32':
def openFolder(path):
subprocess.check_call(['explorer', path])
答案 2 :(得分:8)
以下适用于Macintosh。
import webbrowser
webbrowser.open('file:///Users/test/test_folder')
在GNU / Linux上,使用文件夹的绝对路径。 (确保文件夹存在)
import webbrowser
webbrowser.open('/home/test/test_folder')
正如其他答案中所指出的,它也适用于Windows。
答案 3 :(得分:2)
我认为您可能必须检测操作系统,然后相应地启动相关的文件浏览器。
对于OSX的Finder来说,这可能是有用的:Python "show in finder"
(不幸的是,以下仅适用于Windows)
import webbrowser as wb
wb.open('C:/path/to/folder')
这适用于Windows。 我认为它可以在其他平台上运行。任何人都可以确认吗?仅确认窗口:(
答案 4 :(得分:0)
One approach to something like this is maybe to prioritize readability, and prepare the code in such a manner that extracting abstractions is easy. You could take advantage of python higher order functions capabilities and go along these lines, throwing an exception if the proper function assignment cannot be made when a specific platform is not supported.
import subprocess
import sys
class UnsupportedPlatformException(Exception):
pass
def _show_file_darwin():
subprocess.check_call(["open", "--", path])
def _show_file_linux():
subprocess.check_call(["xdg-open", "--", path])
def _show_file_win32():
subprocess.check_call(["explorer", "/select", path])
_show_file_func = {'darwin': _show_file_darwin,
'linux': _show_file_linux,
'win32': _show_file_win32}
try:
show_file = _show_file_func[sys.platform]
except KeyError:
raise UnsupportedPlatformException
# then call show_file() as usual