简体   繁体   中英

Python for: loop won't pause?

Alright, so I have a script to find, move, and rename files when given a filename to search for. I wrote a wrapper to iterator throughout all my folder in my Robotics folder to automate the process. Here's the code:

#! /usr/bin/env python

import os
import sys
import time

files = [ ... Big long list of filenames ... ]

for item in files:
    sys.stdout.write("Analyzing & Moving " + item + "... ")
    os.system('python mover-s.py "' + item + '"')
    sys.stdout.write("Done.\n")
print ""
print "All files analyzed, moved, and renamed."

Now, it takes ~2s to execute and finished the original script, what I want it to do is display "Analyzing & Moving whatever...." and then AFTER the script is finished, display "Done.". My issue is that both the message and the "Done." message appear at the same time. I've added a small pause to it, about .25s, and the same thing, but it just adds .25s to the time it takes to display "Analyzing & Moving whatever... Done." Basically, why won't it show my first message, pause, then display the second? Because right now it displays the entire line at the same time. This may be because of my poor knowledge of pipes and whatnot..

Add a call to sys.stdout.flush() right after the first write() .

The behaviour you're seeing has to do with buffering. See Usage of sys.stdout.flush() method for a discussion.

There are a couple of issues here.

First, to call another python script, there is no reason to be using os.system as you're currently doing. you should simply have a line along the lines of

import movers # can't have hyphen in a module name
movers.main()

or whatever and let than do it.

Secondly, if you are going to move the files using Python's built-in libraries, see this SO question which explains that you should use shutil.copyfile rather than os.system .

This will also take care of the pause issue.

....
for item in files:
    sys.stdout.write("Analyzing & Moving " + item + "... ")
    os.system('python mover-s.py "' + item + '"')
sys.stdout.write("Done.\n")
print ""
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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