2011-08-20 40 views
8

的输出在Python,如果我使用“wget的”使用使用os.system(“wget的)下载一个文件,它显示像在屏幕上:的Python:如何禁止使用os.system

Resolving... 

Connecting to ... 

HTTP request sent, awaiting response... 

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

等在屏幕上

我能做些什么来保存一些文件,这个输出,而不是显示在屏幕上它

目前我正在运行的命令如下:?

theurl =“<的文件位置> “

downloadCmd =” wget的“+ theurl

使用os.system(downloadCmd)

+3

你为什么要首先调用wget而不是使用python的标准库中的东西? – geoffspear

+0

你可以用一些例子来解释它吗... – nsh

回答

5

要回答你的直接问题,正如其他人所说,你应该认真考虑使用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是你选择的目标路径。有时可能自动确定此值,但方法取决于您的情况。

+0

我收到以下错误:文件“python.py”,第129行 与打开('wget.log','w')作为wgetlog: ^ SyntaxError:无效的语法 – nsh

+0

没有使用关键字“with “和”as“,它工作成功.... wget = Popen(['/ usr/bin/wget',theurl],stdout = PIPE,stderr = STDOUT)stdout,nothing = wget.communicate() wgetlog.write(stdout) – nsh

+0

@nsh是的,对不起。 [with语句](http://docs.python.org/reference/compound_stmts.html#the-with-statement)默认在python 2.6及更高版本中启用,您可以在python 2.5中启用它,方法是添加'from __future__导入with_statement'作为第一个导入。如果您使用的是Python 2.4或以前的版本,请参阅http://stackoverflow.com/questions/3770348/how-to-safely-open-close-files-in-python-2-4 – Marty

0

wget的过程就是写STDOUT(如果有坏事发生也许STDERR),这些都是仍然“连线”到终端。

为了得到它停止这样做,重定向(或接近)说的文件句柄。查看subprocess模块,该模块允许在启动进程时配置所述文件句柄。 (os.system刚刚离开STDOUT/STDERR衍生进程的单独,因此它们是继承,但子模块更加灵活。)

为许多很好的例子和说明,请参见Working with Python subprocess - Shells, Processes, Streams, Pipes, Redirects and More(它引入了标准输入/输出的概念/ STDERR并从那里工作)。

有可能更好的方式来处理这比使用wget - 但我会离开这样对其他的答案。

快乐编码。

+0

我导入了模块子进程。然后我使用它如下-----> process = subprocess.Popen(downloadCmd,shell = False,stdout = subprocess.PIPE)但它给了我错误:File“/usr/lib64/python2.4/文件“/usr/lib64/python2.4/subprocess.py”,行996,在_execute_child中 raise child_exception OSError:[Errno 2]没有这样的文件或目录 – nsh

20

os.system功能通过shell运行命令,所以你可以把任何标准输入输出重定向那里。您还应该使用-q标志(安静)来启动。

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

然而,在Python这样做的更好的方法,如pycurl包装与libcurl,或“股票” urllib2模块。

1

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

但是为了完全控制输出,最好的办法是使用Python subprocess模块而不是os.system()。使用subprocess可让您捕获输出并检查它,或将任意数据输入到标准输入中。

当你想快速和肮脏的方式来运行的东西,使用os.system()。当你想完全控制你的运行方式时,请使用subprocess