在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)
os.system
函数通过shell运行命令,因此您也可以在其中放置任何stdio重定向。您还应该使用wget的-q
标志(quiet)。但是,在python中有更好的方法可以做到这一点,比如libcurl的pycurl包装器,或者“stock”
urllib2
模块。正如其他人所指出的,您可以使用Python本机库模块来执行I/O,也可以修改命令行来重定向输出。
但要完全控制输出,最好使用Python
subprocess
模块,而不是os.system()
。使用subprocess
可以捕获输出并检查它,或者将任意数据馈送到标准输入中。当你想用一种快速而肮脏的方式运行某个东西时,请使用
os.system()
。当您想要完全控制如何运行某个程序时,请使用subprocess
。要回答您的直接问题,正如其他人所提到的,您应该强烈考虑使用subprocess模块。下面是一个例子:
但是,不需要调用系统来下载文件,让python为您做繁重的工作。
使用urllib
或者urllib2
local_filename
是您选择的目标路径。有时可以自动确定这个值,但方法取决于您的环境。相关问题 更多 >
编程相关推荐