Search code examples
pythonmacosblocking

python: unable to find files in recently changed directory (OSx)


I'm automating some tedious shell tasks, mostly file conversions, in a kind of blunt force way with os.system calls (Python 2.7). For some bizarre reason, however, my running interpreter doesn't seem to be able to find the files that I just created.

Example code:

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')

I expect to have a length 1 list with the resulting filename, instead I get an empty list.

The same occurs with

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

I've checked by hand, and the expected files are actually where they're supposed to be.

Also, I was under the impression that os.system blocked, but just in case it doesn't, I also stuck a time.sleep(1) in there before looking for the files. (That's more than enough time for the other tasks to finish.) Still nothing.

Hmm. Help? Thanks!


Solution

  • You should add a wait after the call to launch. Launch will spawn the task in the background and return before the document is finished printing. You can either put in some arbitrary sleep statements or if you want you can also check for file existence if you know what the expected filename will be.

    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)
    

    Alternative:

    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
    

    Reference for potentially needing a longer than 1 second wait here