【问题标题】:Opening Windows Explorer to Specific Path in PyQt properly正确打开 Windows 资源管理器到 PyQt 中的特定路径
【发布时间】:2020-10-20 19:59:04
【问题描述】:

我正在尝试从我的 PyQt 程序中打开一个特定的文件夹。我知道我可以使用 webbrowser 模块 像这样

import webbrowser, os
path="C:/Users"
webbrowser.open(os.path.realpath(path))

或者我可以像这样使用 os.startfile 模块

import os
path = "C:/Users"
path = os.path.realpath(path)
os.startfile(path)

或在 Qt 平台上不推荐的子进程。所以我想知道你怎么能在 PyQt 上正确地做到这一点(也许使用 QProcess?)。我不想打开文件或文件夹对话框,因为我只想打开文件夹而不做任何事情。另外,我想为将来在与 Windows 不同的操作系统上进行更新节省时间,所以我不必更改这部分。是否可以?。非常感谢

【问题讨论】:

    标签: python pyqt explorer


    【解决方案1】:

    一个Qt跨平台的解决方案是使用QDesktopServices::openUrl():

    import os
    import sys
    
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    app = QtWidgets.QApplication(sys.argv)
    
    path = "C:/Users"
    fullpath = os.path.realpath(path)
    
    if not QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(fullpath)):
        print("failed")
    

    【讨论】:

      【解决方案2】:

      我设法使用 QProcess 在特定路径上打开资源管理器,而无需额外的模块(例如 webbrowser)。我只需要platform模块来判断程序运行在哪个平台上,像这样

          self.path = os.path.abspath(os.path.dirname(sys.argv[0]))
          self.pathOutput = os.path.join(self.path, "output")
      
      def open_explorer(self):
          self._process = QtCore.QProcess(self)
          if platform.system() == "Windows":
              self._process.start("explorer",[os.path.realpath(self.pathOutput)])
          elif platform.system() == "Darwin":
              self._process.start("open",[os.path.realpath(self.pathOutput)])
      

      【讨论】:

        猜你喜欢
        • 2012-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 1970-01-01
        相关资源
        最近更新 更多