2

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..

Ech0riginal
  • 329
  • 1
  • 3
  • 7

3 Answers3

4

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

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.

Community
  • 1
  • 1
jdotjdot
  • 16,134
  • 13
  • 66
  • 118
  • I'm using the os.system() method because I want to add an argument, and I just didn't feel like using if __name__ == '__main__': because I've only used it once and not sure of it's usage, and secondly because I don't know a lot about using os.system and thought it'd be a good learning experience :) – Ech0riginal Mar 18 '13 at 15:13
  • 1
    `import mover-s` raises `SyntaxError` because `-` in Python means subtraction, so you can't have a `-` in the name of your module. – gioi Mar 18 '13 at 15:13
  • that is correct, and i probably should have explicitly noted that – jdotjdot Mar 19 '13 at 14:48
0
....
for item in files:
    sys.stdout.write("Analyzing & Moving " + item + "... ")
    os.system('python mover-s.py "' + item + '"')
sys.stdout.write("Done.\n")
print ""
....
Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63