繁体   English   中英

如何使用python抑制Windows文件处理?

[英]How to suppress Windows file handling with python?

我正在Windows中使用Python 2.7和Tkinter运行控制台应用程序。 我正在使用文件浏览器来选择文件。 我的问题是,在用户选择文件和使用路径的脚本之间,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()

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

谢谢JF!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM