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

2024-09-26 18:06:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在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)

Tags: 文件tohttp屏幕osresponserequestwget
3条回答

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

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

但是,在python中有更好的方法可以做到这一点,比如libcurl的pycurl包装器,或者“stock”urllib2模块。

正如其他人所指出的,您可以使用Python本机库模块来执行I/O,也可以修改命令行来重定向输出。

但要完全控制输出,最好使用Pythonsubprocess模块,而不是os.system()。使用subprocess可以捕获输出并检查它,或者将任意数据馈送到标准输入中。

当你想用一种快速而肮脏的方式运行某个东西时,请使用os.system()。当您想要完全控制如何运行某个程序时,请使用subprocess

要回答您的直接问题,正如其他人所提到的,您应该强烈考虑使用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是您选择的目标路径。有时可以自动确定这个值,但方法取决于您的环境。

相关问题 更多 >

    热门问题