【问题标题】:python: unable to find files in recently changed directory (OSx)python:无法在最近更改的目录中找到文件(OSx)
【发布时间】:2016-07-15 07:58:08
【问题描述】:

我正在使用 os.system 调用(Python 2.7)以一种生硬的方式自动化一些乏味的 shell 任务,主要是文件转换。然而,出于某种奇怪的原因,我正在运行的解释器似乎无法找到我刚刚创建的文件。

示例代码:

import os, time, glob

# call a node script to template a word document
os.system('node wordcv.js')

# print the resulting document to pdf
os.system('launch -p gowdercv.docx')

# move to the directory that pdfwriter prints to
os.chdir('/users/shared/PDFwriter/pauliglot')

print glob.glob('*.pdf')

我希望得到一个包含结果文件名的长度为 1 的列表,而不是得到一个空列表。

同样的情况发生在

pdfs = [file for file in os.listdir('/users/shared/PDFwriter/pauliglot') if file.endswith(".pdf")]
print pdfs

我已经手动检查过,预期的文件实际上是它们应该在的位置。

此外,我的印象是 os.system 被阻止了,但以防万一,在查找文件之前,我还在其中粘贴了 time.sleep(1)。 (这对于完成其他任务来说已经绰绰有余了。)仍然没有。

嗯。帮助?谢谢!

【问题讨论】:

    标签: python macos blocking


    【解决方案1】:

    您应该在调用launch 之后添加一个等待。 Launch 将在后台生成任务并在文档完成打印之前返回。您可以输入一些任意的sleep 语句,或者如果您愿意,如果您知道预期的文件名是什么,也可以检查文件是否存在。

    import time
    # print the resulting document to pdf
    os.system('launch -p gowdercv.docx')
    # give word about 30 seconds to finish printing the document
    time.sleep(30)
    

    替代方案:

    import time
    # print the resulting document to pdf
    os.system('launch -p gowdercv.docx')
    # wait for a maximum of 90 seconds
    for x in xrange(0, 90):
        time.sleep(1)
        if os.path.exists('/path/to/expected/filename'):
            break
    

    可能需要超过 1 秒等待的参考 here

    【讨论】:

    • 哇,真的就是这么简单。我现在觉得很笨。 :-) 谢谢!
    最近更新 更多