【问题标题】:How to suppress Windows file handling with python?如何使用 python 抑制 Windows 文件处理?
【发布时间】:2014-04-08 13:14:47
【问题描述】:

我正在使用 Python 2.7 和 Tkinter 在 Windows 中运行控制台应用程序。我正在使用文件浏览器来选择文件。我的问题是,在用户选择文件和使用路径的脚本之间,Windows 也会尝试打开它。在这种情况下,它是一个 .pages 文件,它会尝试使用 Word 打开它。我不希望这种情况发生。怎样才能阻止它>

只是为了上下文,这里是代码:

from Tkinter import *
from tkFileDialog import *
import os.path
import shutil
import sys
import tempfile
from zipfile import ZipFile
import subprocess


class uiclass():
    def __init__(self,root):
        b = Button(root, text="Browse", command=self.callback)
        w = Label(root, text="Please choose a .pages file to convert.")
        w.pack()
        b.pack()

    def callback(self):
        print "click!"
        global y
        y = askopenfilename(parent=root, defaultextension=".pages")
        self.view_file(y)



    def view_file(self,filepath):
        subprocess.Popen(filepath, shell=True).wait()

        PREVIEW_PATH = 'QuickLook/Preview.pdf'  # archive member path
        #pages_file = raw_input('Enter the path to the .pages file in question: ')
        pages_file = y
        pages_file = os.path.abspath(pages_file)
        filename, file_extension = os.path.splitext(pages_file)
        if file_extension == ".pages":
            tempdir = tempfile.gettempdir()
            temp_filename = os.path.join(tempdir, PREVIEW_PATH)
            with ZipFile(pages_file, 'r') as zipfile:
                zipfile.extract(PREVIEW_PATH, tempdir)
            if not os.path.isfile(temp_filename):  # extract failure?
                sys.exit('unable to extract {} from {}'.format(PREVIEW_PATH, pages_file))
            final_PDF = filename + '.pdf'
            shutil.copy2(temp_filename, final_PDF)  # copy and rename extracted file
            # delete the temporary subdirectory created (along with pdf file in it)
            shutil.rmtree(os.path.join(tempdir, os.path.split(PREVIEW_PATH)[0]))
            print('Check out the PDF! It\'s located at "{}".'.format(final_PDF))
            self.view_file(final_PDF) # see Bonus below
            sys.exit()
        else:
            sys.exit('Sorry, that isn\'t a .pages file.')

if __name__ == '__main__':
    root = Tk()
    uiclass(root)
    root.wm_title("Pages to PDF")
    root.mainloop()

【问题讨论】:

  • 是否可以将问题隔离到更小的代码部分?我有点难以理解您的代码中发生了什么,因为全局变量有点奇怪,并且有很多导入的名称。
  • 如果file_extension == ".pages",请勿致电subprocess.Popen(filepath, shell=True).wait()
  • @icedtrees 我认为问题出在else: 之前的最后几行,打开文件的实际代码在哪里。不过我不确定……
  • @J.F.Sebastian 那我应该如何打开 PDF?
  • @evamvid:对 pdf 文件使用 .pdf 扩展名。

标签: python windows python-2.7 tkinter


【解决方案1】:

正如 JFSebastian 所指出的,我的问题是每次循环再次运行时它都会重新打开 PDF(因为 file_extension 变量仍设置为 .pages。有了它,我做了一些更改到解决问题的代码。

谢谢 J.F!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多