2011-08-20 38 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