4

In my code, I write a file to my hard disk. After that, I need to import the generated file and then continue processing it.

for i in xrange(10):
    filename=generateFile()
    # takes some time, I wish to freeze the program here
    # and continue once the file is ready in the system
    file=importFile(filename)
    processFile(file)

If I run the code snippet in one go, most likely file=importFile(filename) will complain that that file does not exist, since the generation takes some time.

I used to manually run filename=generateFile() and wait before running file=importFile(filename).
Now that I'm using a for loop, I'm searching for an automatic way.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
  • 1
    I think you have a good question here. That being said, keep comments in the comments rather than in the post. Other than that, fresh eyes might expect that the program will not advance from `generateFile` until it's done writing/is importable. Is there multithreading at play here? – Prashant Kumar Nov 11 '13 at 04:36
  • Does this answer your question? [Check and wait until a file exists to read it](https://stackoverflow.com/questions/21746750/check-and-wait-until-a-file-exists-to-read-it) – Willie Chalmers III Nov 22 '19 at 20:22

2 Answers2

3

You could use time.sleep and I would expect that if you are loading a module this way you would need to reload rather than import after the first import.

However, unless the file is very large why not just generate the string and then eval or exec it?

Note that since your file generation function is not being invoked in a thread it should be blocking and will only return when it thinks it has finished writing - possibly you can improve things by ensuring that the file writer ends with outfile.flush() then outfile.close() but on some OSs there may still be a time when the file is not actually available.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
0
for i in xrange(10):
    (filename, is_finished)=generateFile()
    while is_finished:
        file=importFile(filename)
        processFile(file)
        continue;

I think you should use a flag to test if the file is generate.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67
  • Will it work? From my intuition, it will just continue without doing anything and miss out one set –  Nov 11 '13 at 11:26