简体   繁体   English

Python for:循环不会暂停?

[英]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. 我在Robotics文件夹中的所有文件夹中都编写了一个用于迭代器的包装程序,以使过程自动化。 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.". 现在,执行并完成原始脚本大约需要2秒钟,我想要它执行的是显示“ Analyzing&Moving what ....”,然后在脚本完成后显示“ 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." 我在上面添加了一个小暂停,大约.25s,也是一样,但是它只是在显示“分析和移动任何东西……完成”的时间上增加了.25s。 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() . 在第一个write()之后立即添加对sys.stdout.flush()的调用。

The behaviour you're seeing has to do with buffering. 您看到的行为与缓冲有关。 See Usage of sys.stdout.flush() method for a discussion. 有关讨论,请参见sys.stdout.flush()方法的用法

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. 首先,要调用另一个python脚本,没有理由像现在那样使用os.system 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 . 其次,如果要使用Python的内置库移动文件,请参见此SO问题该问题说明您应使用shutil.copyfile而不是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 ""
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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