Python:如何保存os.system的输出

9 投票
4 回答
24528 浏览
提问于 2025-04-16 23:59

在Python中,如果我用"wget"通过os.system("wget")来下载文件,屏幕上会显示一些信息,比如:

 Resolving...

 Connecting to ...

 HTTP request sent, awaiting response...

 100%[====================================================================================================================================================================>] 19,535,176  8.10M/s   in 2.3s 

等等,这些信息会在屏幕上显示。

我该怎么做才能把这些输出保存到一个文件里,而不是在屏幕上显示呢?

现在我运行命令的方式是这样的:

theurl = "< file location >"
downloadCmd = "wget "+theurl
os.system(downloadCmd)

4 个回答

1

正如其他人提到的,你可以使用Python自带的库来进行输入输出操作,或者你可以修改命令行来改变输出的方向。

不过,如果你想要完全掌控输出,最好的办法是使用Python的subprocess模块,而不是os.system()。使用subprocess可以让你捕捉输出并查看它,或者将任意数据输入到标准输入中。

当你想快速简单地运行某个命令时,可以用os.system()。但如果你想要完全控制运行的方式,就应该使用subprocess

20

os.system 这个函数是通过一个命令行来运行指令的,所以你可以在这里添加任何标准输入输出的重定向。同时,你也应该在使用 wget 时加上 -q 这个选项(表示安静模式,不输出信息)。

cmd = "wget -q " + theurl + " >/dev/null 2>&1" 

不过,在 Python 中还有更好的方法来实现这个,比如使用 pycurl 这个库的封装,或者使用 Python 自带的 urllib2 模块。

4

直接回答你的问题,正如其他人提到的,你应该认真考虑使用 subprocess 模块。这里有个例子:

from subprocess import Popen, PIPE, STDOUT

wget = Popen(['/usr/bin/wget', theurl], stdout=PIPE, stderr=STDOUT)
stdout, nothing = wget.communicate()    

with open('wget.log', 'w') as wgetlog:
    wgetlog.write(stdout)

不过,不需要调用系统去下载文件,让 Python 来帮你处理这些繁重的工作。

可以使用 urllib

try: 
    # python 2.x
    from urllib import urlretrieve
except ImportError:
    # python 3.x
    from urllib.request import urlretrieve

urlretrieve(theurl, local_filename)

或者使用 urllib2

import urllib2

response = urllib2.urlopen(theurl)
with open(local_filename, 'w') as dl:
    dl.write(response.read())

local_filename 是你选择的目标路径。有时候可以自动确定这个值,但具体方法要看你的情况。

撰写回答