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

nsh*_*nsh 8 python

在Python中,如果我使用"wget"使用os.system("wget")下载文件,它会在屏幕上显示如下:

 Resolving...

 Connecting to ...

 HTTP request sent, awaiting response...

 100%[====================================================================================================================================================================>] 19,535,176  8.10M/s   in 2.3s 
Run Code Online (Sandbox Code Playgroud)

等等在屏幕上.

如何将此输出保存在某个文件中而不是在屏幕上显示?

目前我运行的命令如下:

theurl = "< file location >"
downloadCmd = "wget "+theurl
os.system(downloadCmd)
Run Code Online (Sandbox Code Playgroud)

Kei*_*ith 20

这些os.system函数通过shell运行命令,因此您也可以在其中放置任何stdio重定向.您还应该使用-q标志(安静)来进行wget.

cmd = "wget -q " + theurl + " >/dev/null 2>&1" 
Run Code Online (Sandbox Code Playgroud)

但是,有更好的方法在python中执行此操作,例如libcurl的pycurl包装器或"stock" urllib2模块.


Mar*_*rty 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)
Run Code Online (Sandbox Code Playgroud)

但是,无需调用系统来下载文件,让 python 为您完成繁重的工作。

使用urllib

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

urlretrieve(theurl, local_filename)
Run Code Online (Sandbox Code Playgroud)

或者urllib2

import urllib2

response = urllib2.urlopen(theurl)
with open(local_filename, 'w') as dl:
    dl.write(response.read())
Run Code Online (Sandbox Code Playgroud)

local_filename是您选择的目的地路径。有时可以自动确定该值,但方法取决于您的情况。