0

我正在编写一个 python (2.7) 脚本来检查是否缺少某些文件并通过 wget 下载它们。一切正常,但是在下载完成并且脚本应该退出后,bash(我从中启动 python 脚本)没有正确显示。我有光标并且可以输入内容,但没有显示标准提示。我必须调整终端窗口的大小才能正确显示提示。这可能是什么原因?

tilenames = ['File1', 'File2', ...]
web_url = http://...

for t in tilenames:
    try:
        open(t, 'r')
    except IOError:
        print 'file %s not found.' % (t)
        command = ['wget', '-P', './SRTM/', web_url + t ]
        output = Popen(command, stdout=subprocess.PIPE)

print "Done"

我认为这与调用 wget 进程的方式有关。最后一个命令print "Done"实际上是在 wget 将其所有输出写入 shell 之前完成的。

4

4 回答 4

0

只需添加一个.communicate()后输出,如下所示:

tilenames = ['File1', 'File2', ...]
web_url = http://...

for t in tilenames:
    try:
        open(t, 'r')
    except IOError:
        print 'file %s not found.' % (t)
        command = ['wget', '-P', './SRTM/', web_url + t ]
        p = Popen(command, stdout=subprocess.PIPE)
        stdout, stderr = p.communicate()

print "Done"

communicate将返回写入stdoutNone用于 stderr 的输出,因为它没有转发到 a PIPE(您将在终端上看到它)。

顺便提一句。您应该关闭打开的文件对象(要检查文件是否存在,您可以使用os.path中的函数,例如os.path.exists

于 2012-07-20T13:48:58.267 回答
0

wget 将其统计信息写入stderr,这就是它扰乱您的终端的原因。stdout 和 stderr 会以不同的时间间隔刷新和查询,因此您可能会Donewget.

一个解决方法是调用或重定向wget使用或类似的东西。-qstderrstderr=open("/dev/null", "w")

此外,您可能应该使用它.communicate()来避免管道问题。

于 2012-07-20T13:49:15.867 回答
0

您可以使用 os.system (但请参阅http://docs.python.org/release/2.5.2/lib/node536.html)。基本上 Popen 旨在允许您的 python 进程从命令输出中读取。您似乎不需要这样做,因此下面的片段应该可以满足您的需求:

import os
import subprocess

p = subprocess.Popen(['wget','http://www.aol.com'],stdout=subprocess.PIPE)
os.waitpid(p.pid,0)
print "done"
于 2012-07-20T13:55:51.323 回答
0

如果您将 -q 选项添加到 wget 它也可以工作(相当模式)

于 2020-02-05T22:01:55.003 回答